Related to this question , but this question is about 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. I want to automatically inject these two properties in instances that implement ICommandHandler
.
I found a way to do inject the ILogger
by letting all implementations inherit from a base type and the [SetterProperty]
attribute:
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.
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).
What ways are there to do this more efficiently with StructureMap?
Maybe you could use this?
container.Configure(r => r.For<ICommandHandler>()
.OnCreationForAll(handler =>
{
handler.Logger = container.Resolve<ILogger>();
handler.SendAsync = true;
}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.