【问题标题】:How do I configure mvc core 2 dependency injection with parameters, where one of the parameters is a dependency?如何使用参数配置 mvc core 2 依赖注入,其中一个参数是依赖项?
【发布时间】:2023-03-14 07:10:01
【问题描述】:

如果我有:

public CatManager(ICatCastle catCastle, int something)

我想将其设置为依赖注入,但我不确定如何。

我想我可以做到:

services.AddScoped<ICatCastle, CatCastle>();

services.AddScoped<ICatManager>(new CatManager(???, 42));

但我不确定要输入什么作为 ??? 来获得 CatCastle。每次注入 CatManager 时,我希望它解析一个新的 CatCastle

作为进一步的步骤,我想知道是否可以执行以下操作:

public CatManager(int something)

services.AddScoped<ICatManager>(new CatManager(ResolveICatCastleIntoCatCastle().SomeID));

因此,CatManager 的构造函数会自动使用 ID 调用,而不是获取 ID 的对象。例如,如果它是一个数据库连接,我希望在创建它时进行解析,而不是稍后实际访问属性时。

【问题讨论】:

    标签: c# dependency-injection asp.net-core-mvc-2.0


    【解决方案1】:

    您可以使用工厂委托重载。

    喜欢

    services.AddScoped<ICatManager>(serviceProvider => 
        new CatManager(serviceProvider.GetRequiredService<ICatCastle>(), 42));
    

    我希望它在每次注入 CatManager 时解析一个新的 CatCastle

    如果你想要一座新城堡,那么你需要在一个临时范围内注册CatCastle

    services.AddTransient<ICatCastle, CatCastle>();
    

    关于进一步的步骤public CatManager(int something),可以做类似的方法

    services.AddScoped<ICatManager>(serviceProvider => 
        new CatManager(serviceProvider.GetRequiredService<ICatCastle>().SomeID));
    

    解决依赖关系的位置以及在将其注入依赖类之前执行的操作。

    【讨论】:

    • @NibblyPig 您还应该查看其他答案关于将常量值包装在类中的建议。使 DI 更加简单。前提是您能够重构相关类。
    【解决方案2】:

    您应该将值 42 包装在特定于组件的配置类中,然后注册并注入该配置对象。

    例如:

    public class CatSettings
    {
        public readonly int AnswerToAllCats;
        public CatSettings(int answerToAllCats) => AnswerToAllCats = answerToAllCats;
    }
    
    public class CatManager : ICatManager
    {
        public CatManager(ICatCastle castle, CatSettings settings) ...
    }
    

    配置如下所示

    services.AddScoped<ICatManager, CatManager>();
    services.AddSingleton(new CatSettings(42));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2020-12-20
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多