Simple Injector - 注入容器属性

Frk*_*Frk 4 c# containers ioc-container simple-injector

我想通过 SimpleInjector 注入 Container 属性。我没有找到 SimpleInjector 的任何功能。

然后我想将self Container注册到自己,但是Container没有接口。

我想要这个功能,因为我不通过构造函数传输 Container 对象 - 因为如果我可以使用注册对象的自动注入。

我的使用思路:

var container = new Container();
container.Options.AutowirePropertiesWithAttribute<InjectableProperty>();
container.Register<ISomething, Something>(Lifestyle.Singleton);
Run Code Online (Sandbox Code Playgroud)

ISomething:

public interface ISomething 
{
   void SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)

东西类:

public class Something : ISomething 
{
    public void SomeMethod() 
    {
       var environment = _container.GetInstance<IEnvironment>();
       environment.DoSomething();
    }

    [InjectableProperty] // - maybe it is not possible (I don't know it)
    Container Container {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

你有什么想法来实现这一目标吗?

非常感谢。

Ste*_*ven 5

防止您的应用程序代码依赖于容器。应用程序中唯一应该知道 DI 库存在的地方是Composition Root(注册所有依赖项的地方)。

与其让每个类回调到容器中(称为服务定位器反模式),不如使用依赖注入。使用依赖注入,您可以注入依赖而不是要求它们。

因此,您可以将类重写为以下内容:

public class Something : ISomething 
{
    private readonly IEnvironment environment;

    public Something (IEnvironment environment)
    {
       this.environment = environment;
    }

    public void SomeMethod()
    {
       this.environment.DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,除了存储传入的依赖项之外,还要防止在构造函数中执行任何逻辑。这使您可以自信构建对象图

然而,在某些情况下,将 注入Container到另一个类中仍然很有用。例如,在创建位于Composition Root的工厂类时。在这种情况下,您仍然可以使用构造函数注入,如下所示:

// Defined in an application layer
public interface IMyFactory
{
    IMyService CreateService();
}

// Defined inside the Composition Root
public class MyFactory : IMyFactory
{
    private readonly Container container;

    public MyFactory(Containter container)
    {
        this.container = container;
    }

    public IMyService CreateService(ServiceType type)
    {
        return type == ServiceType.A
            ? this.container.GetInstance<MyServiceA>()
            : this.container.GetInstance<MyServiceB>();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果 Simple Injector 检测到Container构造函数参数,它会自动将自身注入构造函数。