Register open generics with priority

Is it possible to use unity like this:

container.Register(typeof(IMyType<car>), typeof(MyType1<car>));
container.Register(typeof(IMyType<>), typeof(MyType2<>));

.. so when I try to resolve IMyType<car>, I get MyType1<car>... but when I try to resolve IMyType<bus>, do I get MyType2<bus>? Or perhaps another way to do the same, so that a certain common character takes precedence over an open common?

+3
source share
1 answer

Yes, you can do just that:

IUnityContainer container = new UnityContainer();

container.RegisterType(typeof(IMyType<Car>), typeof(MyType1<Car>));
container.RegisterType(typeof(IMyType<>), typeof(MyType2<>));

// Returns MyType1<Car>:
IMyType<Car> car = container.Resolve<IMyType<Car>>();

// Returns MyType2<Bus>:
IMyType<Bus> bus = container.Resolve<IMyType<Bus>>();
+5
source

All Articles