简体   繁体   English

如何使用参数配置mvc core 2依赖项注入,其中参数之一是依赖项?

[英]How do I configure mvc core 2 dependency injection with parameters, where one of the parameters is a dependency?

If I have: 如果我有:

public CatManager(ICatCastle catCastle, int something)

I want to set this up to be dependency injected, but I am not sure how. 我想将其设置为依赖项注入,但不确定如何。

I think I can do this: 我想我可以做到这一点:

services.AddScoped<ICatCastle, CatCastle>();

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

But I am not sure what to put in as the ??? 但是我不知道要放什么??? to get the CatCastle. 获得CatCastle。 I'd like it to resolve a new CatCastle every time CatManager is injected. 我想它来解决新的CatCastle每次CatManager注入。

As a further step, I wonder if it possible to do something like: 作为进一步的步骤,我想知道是否可以执行以下操作:

public CatManager(int something)

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

So that CatManager's constructor is automatically invoked with the ID, but not the object that gets the IDs. 这样,CatManager的构造函数将自动使用ID进行调用,而不是使用获取ID的对象。 For example, if it is a database connection I want that resolution to occur when it is created and not later on when the property is actually accessed. 例如,如果它是数据库连接,则我希望该分辨率在创建它时发生,而不是稍后在实际访问该属性时发生。

You can use the factory delegate overload. 您可以使用工厂委托重载。

Like 喜欢

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

I'd like it to resolve a new CatCastle every time CatManager is injected. 我想它来解决新的CatCastle每次CatManager注入。

If you want a new castle then you need to register CatCastle with a transient scope 如果您想要一座新城堡,则需要使用临时范围注册CatCastle

services.AddTransient<ICatCastle, CatCastle>();

Regarding the further step public CatManager(int something) , a similar approach can be done 关于public CatManager(int something)的进一步步骤,可以执行类似的方法

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

where the dependency is resolved and what ever action is performed before injecting it into the dependent class. 在解决依赖项的位置以及将其注入到依赖类之前执行的操作。

You should wrap the value 42 in a component-specific configuration class and register and inject that configuration object instead. 您应该将值42包装在特定于组件的配置类中,然后注册并注入该配置对象。

For instance: 例如:

public class CatSettings
{
    public readonly int AnswerToAllCats;
    public CatSettings(int answerToAllCats) => AnswerToAllCats = answerToAllCats;
}

public class CatManager : ICatManager
{
    public CatManager(ICatCastle castle, CatSettings settings) ...
}

The configuration would then look like 然后,配置看起来像

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

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

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