简体   繁体   English

如何使用Simple Injector将依赖项注入Base类?

[英]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? 如何在SimpleInjector容器中注册Rectangle接口,同时将ILogger注入其基类Shape

The purpose of doing this is to make the derived class not concerned about the ILogger . 这样做的目的是使派生类不关心ILogger The ILogger is an infrastructure service which is used to log some values to the file for debugging purpose. ILogger是一种基础结构服务,用于将某些值记录到文件中以进行调试。

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: 要实现这一点,您必须通过派生类的构造函数公开logger:

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). 这使基类保持干净,甚至通常允许完全删除基类(或者使其纯粹抽象,或者用接口替换它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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