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?
MyBar
you should look for a way to tell the service container that in order to resolveIFoo
, it can resolveIBar
and cast down, otherwise each of the two interfaces will typically resolve to two distinct instances of theMyBar
class. – Lasse V. Karlsen