Configure Unity for Inherted Interfaces
I am fairly new to Unity, (well, IoC and DI in general), and am having problems configuring it for my use.
I have two interfaces:
public i开发者_C百科nterface ISample { ... }
and
public interface IDerivedSample : ISample { ... }
and a number of concreate classes simular to:
public class UseSample : IDerivedSample { ... }
I am attempting to configure Unity to resolve these when used like this:
public class UsesSample
{
private ISample _sample;
public UsesSample(ISample sample)
{
_sample = sample;
}
}
My attempts at getting this configured is failing, so I thought I would ask the crowd on how to do so.
EDIT
I have already configured the container to find the different versions of the interfaces by name, so the resulting code for resolving UserSample should be simular to:
ISample = contianer.Resolve<ISample>("derived");
However, it is failing.
The short answer
container.RegisterType<ISample, UseSample>();
The longer answer
The code above works if you only register one mapping from ISample
to a concrete class. As I read your question, you have many implementations of ISample
, in which case ambiquity arises because the UsesSample
provides no hint at how to pick a proper ISample
instance.
There are several ways out of such a conundrum. Some are specific to the DI Container (in this case Unity) while others solve the issue by creating a less ambiguous API design.
You may, for example, use an Abstract Factory to select a dependency based on a run-time value.
精彩评论