如何使用DryIOC解析使用父层次结构接口

时间:2016-06-21 12:15:26

标签: c# dryioc

我有以下对象结构

public interface IParser {}
public interface IAction : IParser {}
public interface ICommand : IParser {}

//impl
public class Action1 : IAction {}
public class Command1 : ICommand {}

//registration
container.Register<IAction, Action1>();
container.Register<ICommand, Command1>();

//resolve
var parsersList = container.Resolve<IList<IParser>>() //expected: parsersList.Count=2 actual count=0

有没有办法在DryIOC中的这些父接口和子接口之间进行某种绑定?

编辑:

我做了一些研究,发现RegisterMany做了这个伎俩,但我有点困惑,因为

//registration
//container.Register<IAction, Action1>(); //if I drop these two lines \_____
//container.Register<ICommand, Command1>();                           /     |
container.RegisterMany<Action1>(); // and use these lines                   |
container.RegisterMany<Command1>();                                         |
//resolve                                                                   |
var parsersList = container.Resolve<IList<IParser>>() //WORKS Count = 2     |
container.Resolve<IAction>() //not working Unable to resolve IAction    <---|
container.Resolve<ICommand>() //Same here for ICommand                  <---|
container.Resolve<IParser>() //not working either

如果我取消注释上面的个人注册行,Resolve适用于IAction和ICommand,但不适用于IParser。

似乎RegisterMany没有正确注册父类型......

EDIT2:

我使用RegisterMapping

将注册更改为关注
container.Register<IAction, Action1>();
container.Register<ICommand, Command1>();
container.RegisterMapping<IParsable, ICommand>(); //1st registered mapping
container.RegisterMapping<IParsable, IAction>();
container.Resolve<IList<IParser>>().Count = 1 //instead of 2.

IParsers列表中的项目是第一个注册映射的类型,在本例中为ICommand

我正在使用DryIOC v2.6.2

1 个答案:

答案 0 :(得分:2)

这是工作和解释sample on .NET Fiddle

代码:

    var container = new Container();

    container.RegisterMany<Action1>();                 
    container.RegisterMany<Command1>();

    var parsersList = container.Resolve<IList<IParser>>();

    // works fine
    container.Resolve<IAction>();

    // works fine
    container.Resolve<ICommand>();

    // Throws because IParser is registered multiple times (as Action and as Command),
    // and container is unable to select one. This is precisely what exception is saying.
    //container.Resolve<IParser>();

DryIoc中的异常应该在这种情况下引导你。

更新

如果您想要包含RegisterMany使用的非公共服务类型:

container.RegisterMany<Action1>(nonPublicServiceTypes: true);                 
container.RegisterMany<Command1>(nonPublicServiceTypes: true);