[英]How do I configure mvc core 2 dependency injection with parameters, where one of the parameters is a dependency?
如果我有:
public CatManager(ICatCastle catCastle, int something)
我想将其设置为依赖项注入,但不确定如何。
我想我可以做到这一点:
services.AddScoped<ICatCastle, CatCastle>();
services.AddScoped<ICatManager>(new CatManager(???, 42));
但是我不知道要放什么???
获得CatCastle。 我想它来解决新的CatCastle
每次CatManager
注入。
作为进一步的步骤,我想知道是否可以执行以下操作:
public CatManager(int something)
services.AddScoped<ICatManager>(new CatManager(ResolveICatCastleIntoCatCastle().SomeID));
这样,CatManager的构造函数将自动使用ID进行调用,而不是使用获取ID的对象。 例如,如果它是数据库连接,则我希望该分辨率在创建它时发生,而不是稍后在实际访问该属性时发生。
您可以使用工厂委托重载。
喜欢
services.AddScoped<ICatManager>(serviceProvider =>
new CatManager(serviceProvider.GetRequiredService<ICatCastle>(), 42));
我想它来解决新的
CatCastle
每次CatManager
注入。
如果您想要一座新城堡,则需要使用临时范围注册CatCastle
services.AddTransient<ICatCastle, CatCastle>();
关于public CatManager(int something)
的进一步步骤,可以执行类似的方法
services.AddScoped<ICatManager>(serviceProvider =>
new CatManager(serviceProvider.GetRequiredService<ICatCastle>().SomeID));
在解决依赖项的位置以及将其注入到依赖类之前执行的操作。
您应该将值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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.