我如何在温莎城堡注册?

时间:2015-02-19 01:11:00

标签: c# 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的依赖。

1 个答案:

答案 0 :(得分:1)

您可以使用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; }
}