且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用不同的依赖两次注册相同的类

更新时间:2023-02-05 19:08:01

我不知道这是否是更接近你问对,但是,你可以用
ServiceOverride.ForKey 来指定哪些参数映射到的名称:

I'm not sure if this is closer to what you're asking for, but, you can use ServiceOverride.ForKey to specify which parameters map to which names:

Component.For<Bar>().ImplementedBy<Bar>().
    DependsOn(ServiceOverride.ForKey("fooAbc").Eq("abc")).
    DependsOn(ServiceOverride.ForKey("foo123").Eq("123"))
);



另外,没有直接回答,但你有一个选项是解决一个的IEnumerable&LT;的IFoo&GT; 。这是一个很好的选择,如果你确实有的IFoo 任意数量来解决。

Alternatively, not a direct answer, but an option you have is to resolve an IEnumerable<IFoo>. This is a good option if you actually have an arbitrary number of IFoo to resolve.

如果你改变了定义律师接受了的IEnumerable

If you change the definition of Bar to accept an IEnumerable

public class Bar
{
    private readonly IEnumerable<IFoo> _foos;

    public Bar(IEnumerable<IFoo> foos)
    {
        _foos = foos;
    }
}



然后为注册和解析。你需要你做登记之前添加的决心

Then to register and resolve. You need to add the Resolve before you do the registrations.

var container = new WindsorContainer();

container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));

container.Register(
    Component.For<IFoo>().Instance(new Foo("abc")).Named("abc"),
    Component.For<IFoo>().Instance(new Foo("123")).Named("123"),
    Component.For<Bar>().ImplementedBy<Bar>());