StructureMap:在基类中注入原始属性

时间:2011-04-20 19:56:46

标签: c# .net dependency-injection ioc-container structuremap

与此question相关,但此问题与StructureMap有关。

我有以下界面定义:

public interface ICommandHandler
{
    ILogger Logger { get; set; }
    bool SendAsync { get; set; }
}

我有多个实现ICommandHandler的实现,需要解决。我想在实现ICommandHandler的实例中自动注入这两个属性。

我找到了一种注入ILogger的方法,让所有实现都继承自基类型和[SetterProperty]属性:

public abstract class BaseCommandHandler : ICommandHandler
{
    [SetterProperty]
    public ILogger Logger { get; set; }

    public bool SendAsync { get; set; }
}

然而,这并没有帮助我在所有实现中注入原始bool类型。

命令处理程序实现从基接口继承的通用接口:

public interface ICommandHandler<TCommand> : ICommandHandler
    where TCommand : Command
{
     void Handle(TCommand command);
}

这是我目前的配置:

var container = new Container();

container.Configure(r => r
    .For<ICommandHandler<CustomerMovedCommand>>()
    .Use<CustomerMovedHandler>()
    .SetProperty(handler =>
    { 
        handler.SendAsync = true;
    }));

container.Configure(r => r
    .For<ICommandHandler<ProcessOrderCommand>>()
    .Use<ProcessOrderHandler>()
    .SetProperty(handler =>
    { 
        handler.SendAsync = true;
    }));

container.Configure(r => r
    .For<ICommandHandler<CustomerLeftCommand>>()
    .Use<CustomerLeftHandler>()
    .SetProperty(handler =>
    { 
        handler.SendAsync = true;
    }));

// etc. etc. etc.

正如您所看到的,我为每个配置设置了属性,这非常麻烦(但是,SetProperty接受Action<T>委托是非常好的。)

有哪些方法可以更有效地使用StructureMap?

1 个答案:

答案 0 :(得分:2)

也许你可以用它?

container.Configure(r => r.For<ICommandHandler>()
    .OnCreationForAll(handler =>
    {
        handler.Logger = container.Resolve<ILogger>();
        handler.SendAsync = true;
    }));