简体   繁体   中英

Simple Injector: Injecting a property in a base class

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM