Register open generics with precedence
Is it possible to use unity like so:
container.Register(typeof(IMyType<car>)开发者_如何学运维, typeof(MyType1<car>));
container.Register(typeof(IMyType<>), typeof(MyType2<>));
.. so that when I try to resolve IMyType<car>
I get a MyType1<car>
... but when I try to resolve IMyType<bus>
I get MyType2<bus>
? Or perhaps another way to do the same thing so that a defined generic takes precedence over an open generic?
Yes, you can do exactly 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>>();
精彩评论