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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With