简体   繁体   中英

How can I inject dependencies to the Base class with Simple Injector?

How can I register the Rectangle interface in a SimpleInjector container, at the same time ILogger is injected to it's base class Shape also?

The purpose of doing this is to make the derived class not concerned about the ILogger . The ILogger is an infrastructure service which is used to log some values to the file for debugging purpose.

public class Shape : IShape
{
    public void Shape(ILogger logger){}
    public virtual void Draw(){}
}

public class Rectanble : Shape
{
    public void Reactangular();
    public override void Draw(){}
}

To achieve this, you will have to expose logger through the constructor of the derived class:

public class Rectangle : Shape
{
    public Rectangle(ILogger logger) : base(logger) { }
    public override void Draw(){}
}

Do note that base classes that handle cross-cutting concerns like logging is a strong indication of violating the Single Responsibility Principle. These base classes easily become ever changing classes that contain lots of dependencies, making the derived classes harder to test and maintain.

Instead of having base classes with dependencies, it's usually much better to implement cross-cutting concerns using decorators. This keeps the base class clean and often even allows the removal of the base class altogether (or making it purely abstraction, or replace it with an interface).

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