Search code examples
.netinversion-of-controlunity-containeropen-generics

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?


Solution

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