【问题标题】:DependencyInjection: Initialize class, before it is called (required)?DependencyInjection:在调用之前初始化类(必需)?
【发布时间】:2019-03-05 05:22:45
【问题描述】:

首先,我使用的是微软的依赖注入包。 (ServiceProvider, ServiceCollection) 目前进展顺利,除了这个问题。

我有课程,我像这样注册到我的 DI

this.AddSingleton<IAppWorker, AppWorker>();
this.AddSingleton<IAppController, AppController>();

这些类永远不会被访问,但它们会在它们的构造函数中调用一个方法。我真的需要显式解析类,并在构造函数之外调用方法吗?

或者有没有办法让它只是初始化一个新实例,并在我需要解决它时存储它?我对此很陌生,甚至很难知道要搜索什么。

这个有什么特别的名字吗?还是根本不可能。

【问题讨论】:

    标签: c# .net dependency-injection .net-core


    【解决方案1】:

    您可以在组合根目录中创建实例,并使用AddSingleton&lt;TService&gt;(IServiceCollection, TService) 重载将它们添加到 DI 容器中。

    TService 中指定类型的单例服务与implementationInstance 中指定的实例添加到指定的IServiceCollection

    var instance1 = new AppWorker();
    services.AddSingleton<IAppWorker>(instance1);
    
    var instance2 = new AppController();
    services.AddSingleton<IAppController>(instance2);
    

    参考Dependency injection in ASP.NET Core

    【讨论】:

      【解决方案2】:

      不确定您要完成什么。建议避免向构造函数添加逻辑。最好使用构造函数注入来解析这些实例,并在需要时调用这些方法。

      如果您对此不熟悉,我会建议“.NET 书籍中的依赖注入 (https://www.manning.com/books/dependency-injection-in-dot-net-second-edition)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        • 1970-01-01
        • 2016-12-30
        • 2014-06-24
        • 1970-01-01
        • 2022-08-16
        相关资源
        最近更新 更多