[英]C# IoC configuration: how can I inject an object when one of its parameters it's not an already injected object?
I'm using the Microsoft.Extensions.DependencyInjection
library and I have this concrete class which implements a generic interface called IInterface
我正在使用
Microsoft.Extensions.DependencyInjection
库,并且我有这个具体的类,它实现了一个名为IInterface
的通用接口
using System.Net.Http;
namespace my.namespace
{
public class Concrete : IInterface
{
private readonly IHttpClientFactory _factory;
private readonly string _s1;
private readonly string _s2;
public Concrete(IHttpClientFactory factory, string s1, string s2)
{
_factory = factory;
_s1 = s1;
_s2 = s2;
}
}
}
In my IocConfig.cs I'm injecting the IHttpClientFactory
, like this:在我的 IocConfig.cs 中,我正在注入
IHttpClientFactory
,如下所示:
services.AddHttpClient("clientName", client =>
{
});
Now I also want to inject the Concrete
class.现在我还想注入
Concrete
类。 Since the s1 and s2 parameters are outside my already defined dependencies I think I should use the explicit constructor, like this:由于 s1 和 s2 参数超出了我已经定义的依赖项,我认为我应该使用显式构造函数,如下所示:
services.AddScoped<IInterface, Concrete>(sp => new Concrete(/* parameters */));
If all the parameters required by the constructor would have been already defined dependencies I should have done it this way:如果构造函数所需的所有参数都已经定义了依赖项,我应该这样做:
services.AddScoped<IOtherInterface, OtherConcrete>();
How can I inject this class correctly providing all the parameters needed?如何正确注入此类提供所需的所有参数? I think I need to explicitly pass IHttpClientFactory and also both s1 and s2 strings but I don't know how to do it.
我想我需要明确传递 IHttpClientFactory 以及 s1 和 s2 字符串,但我不知道该怎么做。
The lambda function passed to AddScoped
takes an IServiceProvider
as input.传递给
AddScoped
的 lambda 函数将IServiceProvider
作为输入。 You can use this to resolve an IHttpClientFactory
by calling GetService<IHttpClientFactory>()
.您可以通过调用
GetService<IHttpClientFactory>()
来使用它来解析IHttpClientFactory
。
services.AddScoped<IInterface, Concrete>(sp
=> new Concrete(sp.GetService<IHttpClientFactory>(), "s1", "s2"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.