Conditionally resolve named implementation in Unity

扶醉桌前 提交于 2019-12-05 05:35:11

You could you the InjectionFactory of Unity to inject a named instance.

var container = new UnityContainer();

// register
container.Register<IFish, OneFish>("One");
container.Register<IFish, TwoFish>("Two");

container.RegisterType<ITank,Tank>(new InjectionFactory(c=>c.Resolve<IFish>("One")));

If you now resolve an instance of type Tank, an instance of OneFish is injected to your Tank.

To handle your case that you want to inject a default implemenation of IFish you can change InjectionFactory to the following

new InjectionFactory(c=>{
  if (c.IsRegistered<IFish>("One")) {
    c.Resolve<IFish>("One");
  }
  else {
    c.Resolve<IFish>("Two");
  }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!