Search code examples
c#unity-container

Interface inheritance and Unity resolve


I am trying to resolve a object through it's base interface using Unity. If I have the following interfaces and classes:

interface IFoo { }
interface IBar : IFoo { }
class MyBar : IBar { }

and I want to inject MyBar into multiple classes like so:

class DoSomething
{
    public DoSomething(IFoo myBar) 
    { 
        // Execute a method from IFoo implementation 
    }
}

class DoSomethingElse
{
    public DoSomethingElse(IBar myBar) 
    { 
        // Execute a method from IBar **AND** IFoo implementation 
    }
}

If I register MyBar like this:

container.RegisterType<IBar, MyBar>();

Unity throws an error trying to resolve for IFoo (see the DoSomething constructor). But IBar inherits from IFoo?

I could register MyBar twice with the container like this:

container.RegisterType<IFoo, MyBar>();
container.RegisterType<IBar, MyBar>();

but it feels like I should not have to do this. I might be wrong here.

So my question is if Unity can resolve a class from its base interface?


Solution

  • Basically a DI-container tries to create instances of interfaces by some sort of mapping. So when you write

    container.RegisterType<IBar, MyBar>();
    

    the container knows, whenever I am requested to create some instance for IBar I resolve that call by instantiating MyBar.

    However the container doesn´t know what to do what do if he is requested for an instance of IFoo, because not every IFoo is an IBar. So what should be returned when writing this:

    container.GetInstance<IFoo>();
    

    In your case only a single type is possible, IBar for which in turn also only a single type is possible. This however contradicts the purpose of interfaces, as in fact it´s allways bounded to one specific type, while it should work with any type implementing that interface.

    That´s why you have to determine a mapping for both interfaces.