Unity container object resolution hierarchy
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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论