问题
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.
回答1:
The Simple Injector documentation on property injection gives a very clear explanation about this. The basic options are:
- Register an initialization delegate using
RegisterInitializer
. - Override Simple Injector's
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.
来源:https://stackoverflow.com/questions/6227074/simple-injector-injecting-a-property-in-a-base-class