Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap: Injecting a primitive property in a base class

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?

like image 641
Steven Avatar asked Nov 05 '22 23:11

Steven


1 Answers

Maybe you could use this?

container.Configure(r => r.For<ICommandHandler>()
    .OnCreationForAll(handler =>
    {
        handler.Logger = container.Resolve<ILogger>();
        handler.SendAsync = true;
    }));
like image 162
František Žiačik Avatar answered Nov 09 '22 16:11

František Žiačik