简体   繁体   English

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

[英]StructureMap: Injecting a primitive property in a base class

Related to this question , but this question is about StructureMap. 与此问题相关,但这个问题与StructureMap有关。

I have got the following interface definition: 我有以下接口定义:

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

I have multiple implementations that implement ICommandHandler and need to be resolved. 我有多个实现ICommandHandler实现,需要解决。 I want to automatically inject these two properties in instances that implement ICommandHandler . 我想在实现ICommandHandler实例中自动注入这两个属性。

I found a way to do inject the ILogger by letting all implementations inherit from a base type and the [SetterProperty] attribute: 我找到了一种方法来通过让所有实现继[SetterProperty]类型和[SetterProperty]属性来注入ILogger

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

    public bool SendAsync { get; set; }
}

This however, doesn't help me with injecting the primitive bool type in all implementations. 然而,这并没有帮助我在所有实现中注入原始bool类型。

The command handlers implement a generic interface that inherits from the base interface: 命令处理程序实现从基接口继承的通用接口:

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

Here is my current configuration: 这是我目前的配置:

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.

As you can see, I set the property for each and every configuration, which is quite cumbersome (however, it is pretty nice that the SetProperty accepts a Action<T> delegate). 正如您所看到的,我为每个配置设置了属性,这非常麻烦(但是, SetProperty接受Action<T>委托非常好)。

What ways are there to do this more efficiently with StructureMap? 有哪些方法可以更有效地使用StructureMap?

Maybe you could use this? 也许你可以用这个?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM