开发者

Unity container object resolution hierarchy

开发者 https://www.devze.com 2023-03-11 22:55 出处:网络
I have my container configured like following: container = new UnityContainer() .RegisterType<IA, A>()

I have my container configured like following:

container = new UnityContainer()
            .RegisterType<IA, A>()
            .RegisterType<IB, B>()
            .RegisterType<IC, C>(new InjectionConstructor(strA));

What I need is, I want to register another C instance like:

container.RegisterType<IC, C>(new InjectionConstructor(strB));

note the difference between strA and strB.

Both A and开发者_StackOverflow社区 B need C. But I want A to use the first C and B to use the second C.

Is there a proper way in Unity to achieve that?

Thanks


You will want to use a named type registration.

var container = new UnityContainer()
  .RegisterType<IC, C>("ForA", new InjectionConstructor(strA))
  .RegisterType<IC, C>("ForB", new InjectionConstructor(strB))

  .RegisterType<IA, A>(new InjectionConstructor(container.Resolve<IC>("ForA")))
  .RegisterType<IB, B>(new InjectionConstructor(container.Resolve<IC>("ForB")));


I've accomplished this in the past by decorating/facading the common interfaces in order to identify them for mappings.

// new interface just for A
public interface ICforA : IC { }

// new interface just for B
public interface ICforB : IC { }

container = new UnityContainer()
           .RegisterType<IA, A>()
           .RegisterType<IB, B>()
           .RegisterType<ICforA, C>(new InjectionConstructor(strA));
           .RegisterType<ICforB, C>(new InjectionConstructor(strB));

Disclaimer: Code written from memory, not Visual Studio.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号