我如何在 Castle Windsor 中注册这个?

How do would I register this in Castle Windsor?

public interface IDo
{
    ... details 
}
public class DoOneThing : IDo
{
    ...
}
public class DoAnotherThing : IDo
{
    ....
}

public interface IFooService
{
    ... details
}

public class FooService
{
    private IDo do;

    public FooService(IDo do)
    {
        // instance is of type specifically resolved per call
        this.do = do;
    }


    ...
}

Container.Register(ComponentFor<IDo>().ImplementedBy<DoOneThing>().Named("DoOneThing");
Container.Register(ComponentFor<IFooService>().ImplementedBy<FooService>().DependsOn(Dependency.OnComponent(typeof(IDo), "DoOneThing")).Named("DoItWithOneThing");
Container.Register(ComponentFor<IFooService>().ImplementedBy<FooService>().DependsOn(Dependency.OnComponent(typeof(IDo), "DoAnotherThing")).Named("DoItWithAnotherThing");



Container.Resolve<IFooService>("DoItWithOneThing");

如何注册 FooService 使其具有 IDo 类型的依赖项,然后使用特定的实现类型进行解析?我试过使用类似上面代码的方法,但出现异常,找不到服务组件。如果我尝试解析命名实例,它会告诉我它正在等待 DoOneThing 的依赖项。

您可以使用 Castle Windsor - multiple implementation of an interface 中提到的键入 Dependency.OnComponent

另请参阅:Castle Project -- Inline dependencies

var container = new WindsorContainer();

container.Register(
    Component
        .For<IDo>()
        .ImplementedBy<DoAnotherThing>());

container.Register(
    Component
        .For<IDo>()
        .ImplementedBy<DoOneThing>());

container.Register(
    Component
        .For<IFooService>()
        .ImplementedBy<FooService>()
        .Named("DoItWithOneThing")
        .DependsOn(
            Dependency.OnComponent<IDo, DoOneThing>()));

container.Register(
    Component
        .For<IFooService>()
        .ImplementedBy<FooService>()
        .Named("DoItWithAnotherThing")
        .DependsOn(
            Dependency.OnComponent<IDo, DoAnotherThing>()));

测试

var doItWithOneThing = container.Resolve<IFooService>("DoItWithOneThing");
var doItWithAnotherThing = container.Resolve<IFooService>("DoItWithAnotherThing");

Console
    .WriteLine(
        "doItWithOneThing.Do is DoOneThing // {0}",
        doItWithOneThing.Do is DoOneThing);
Console
    .WriteLine(
        "doItWithAnotherThing.Do is DoAnotherThing // {0}",
        doItWithAnotherThing.Do is DoAnotherThing);

输出

doItWithOneThing.Do is DoOneThing // True
doItWithAnotherThing.Do is DoAnotherThing // True

声明

public interface IDo {}
public class DoOneThing : IDo {}
public class DoAnotherThing : IDo {}
public interface IFooService
{
    IDo Do { get; }
}

public class FooService : IFooService
{
    public FooService(IDo @do)
    {
        Do = @do;
    }

    public IDo Do { get; private set; }
}