Conditionally allow named implementation in Unity

Unity allows you to name different implementations of the same interface, and then resolve them by name:

var container = new UnityContainer(); // register container.Register<IFish, OneFish>("One"); container.Register<IFish, TwoFish>("Two"); // resolve var twoFish = container.Resolve("Two"); 

Now suppose I have a class that depends on IFish and implements ITank:

 class Tank : ITank { public Tank(IFish fish) {...} } 

How can I enable ITAN and specify which IFish implementation to get?

This does not work:

 container.Register<ITank, Tank>(); var tank = container.Resolve<ITank>("One"); 

It works:

 var fish = container.Resolve<IFish>("One"); var tank = container.Resolve<Tank>(new DependencyOverride(typeof(IFish), fish); 

but it only handles simple cases (for example, in this example), and not a general case where there can be many implementations with the name "One". I want to be able to say Unity:

"If you allow the use of implementations with the name" One ", if such an implementation is not a registry, it goes back to the unnamed implementation"

Is there a custom resolver that can be connected to Unity with this behavior?

+6
source share
1 answer

You can enter InjectionFactory of Unity for 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 enable an instance of type Tank, an instance of OneFish is injected into your Tank.

To handle your case, which you want to implement by default for IFish, you can change the InjectionFactory to the following

 new InjectionFactory(c=>{ if (c.IsRegistered<IFish>("One")) { c.Resolve<IFish>("One"); } else { c.Resolve<IFish>("Two"); } }) 
+3
source

Source: https://habr.com/ru/post/955220/


All Articles