AutoFac从特定派生服务中解析CommandHandler

时间:2017-02-08 17:42:56

标签: c# autofac

注意:这与此Question

类似

我的问题是,如果我有如下定义的接口:
(注意:我的代码有多个派生级别;为简单起见示例)

from itertools import accumulate, chain, tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

[s[a:b] for a, b in pairwise(accumulate(chain([0], keys)))]

此示例的注册片段如下所示:

public interface IHandler
{
    void Handle(IBaseCommand command);
}

public interface IHandler<out T> : IHandler where T : IBaseCommand { }

public interface IBaseCommand { }
public interface IDerivedCommand : IBaseCommand { }
public class BaseCommand : IBaseCommand { }
public class DerivedCommand : IDerivedCommand { }

public class BaseCommandHandler : IHandler<IBaseCommand>
{
    public void Handle(IBaseCommand command) { }
}

public class DerivedCommandHandler : IHandler<IDerivedCommand>
{
    public void Handle(IBaseCommand command) { }
    public void Handle(IDerivedCommand command) { }
}

builder.RegisterType<DerivedCommand>().AsImplementedInterfaces(); builder.RegisterType<BaseCommand>().AsImplementedInterfaces(); builder.RegisterType<DerivedCommandHandler>().AsImplementedInterfaces(); builder.RegisterType<BaseCommandHandler>().AsImplementedInterfaces(); 仅返回container.Resolve<IEnumerable<IHandler<IBaseCommand>>>();

我需要获取BaseCommandHandler和所有派生类型,在这种情况下也会包含BaseCommandHandler

我意识到此注册DerivedCommandHandler将解析所有处理程序,但我需要能够解析派生链中的任何位置。

问题:如何从特定的派生服务开始解析所有处理程序?

1 个答案:

答案 0 :(得分:0)

你可以改变这个:

IHandler<out T>

为:

IHandler<in T>