开发者

Register open generics with precedence

开发者 https://www.devze.com 2023-03-10 22:25 出处:网络
Is it possible to use unity like so: container.Register(typeof(IMyType<car>)开发者_如何学运维, typeof(MyType1<car>));

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>>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号