6

我有以下对象结构

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没有正确注册父类型......

编辑2:

我将注册更改为以下,使用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

4

1 回答 1

3

这是.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);
于 2016-06-22T08:30:17.460 回答