For several weeks I've been using the Simple Injector dependency injection container, with great success. I love the easy by which I can configure it. But now I have a design that I don't know how to configure. I have a base class where many types from derive, and I want to inject a dependency into a property of the base class, but without having to configure that for every derived class. I tried to do this with attributes, but Simple Injector does not support attributes. Here is a trimmed down version of my design.
public interface Handler<TMessage> where TMessage : Message
{
void Handle(TMessage message);
}
public abstract class BaseHandler
{
// This property I want to inject
public HandlerContext Context { get; set; }
}
// Derived type
public class NotifyCustomerHandler : BaseHandler,
Handler<NotifyCustomerMessage>
{
public NotifyCustomerHandler(SomeDependency dependency)
{
}
public void Handle(NotifyCustomerMessage message)
{
}
}
My configuration now looks like this:
container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here
How can I inject the property in the BaseHandler?
Thanks in advance for any help.
Property injection is a type of dependency injection where dependencies are provided through properties. Visit the Dependency Injection chapter to learn more about it. Let's understand how we can perform property injection using Unity container. Consider the following example classes.
A Simple Injector is an easy, flexible, and fast dependency injection library. The purpose of a Simple Injector is to provide . NET application developers with an easy, flexible, and fast Inversion of Control library that uses best practices to steer developers to success.
The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
The Simple Injector documentation on property injection gives a very clear explanation about this. The basic options are:
RegisterInitializer
.PropertySelectionBehavior
.As the documentation explains, the use of RegisterInitializer
is not advised for property injection on dependencies; only on configuration values.
This leaves you with overriding Simple Injector's PropertySelectionBehavior
, but having a base class by itself smells like a SOLID violation. Please take a look at the following article. It describes why having a base class might be a bad idea and the article presents a solution for this.
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