C# 将一个参数传递给依赖项注入类的构造函数,该构造函数也将有一个依赖项注入参数

C# 将一个参数传递给依赖项注入类的构造函数,该构造函数也将有一个依赖项注入参数,c#,asp.net,.net,dependency-injection,C#,Asp.net,.net,Dependency Injection,我正在将.net framework转换为.net 5.0,并使用.net 5.0中内置的依赖项注入,而不是.net framework中使用的Ninject库 我有以下构造函数,它接受messageHandler(通过依赖项注入)和web服务根地址: public class MyConfig { public string WebServiceRootAddress { get; set; } } (旧)1 以下是通过.net framework中的ninject进行依赖项注入的设

我正在将.net framework转换为.net 5.0,并使用.net 5.0中内置的依赖项注入,而不是.net framework中使用的Ninject库

我有以下构造函数,它接受messageHandler(通过依赖项注入)和web服务根地址:

public class MyConfig
{
    public string WebServiceRootAddress { get; set; }
}
(旧)1

以下是通过.net framework中的ninject进行依赖项注入的设置:

(旧)2

kernel.Bind().To().InSingletonScope()
.带构造函数参数(
“webServiceRootAddress”,
AppSettings[“webServiceRootAddress”]);
(旧)3

kernel.Bind().To();
我想在启动文件中的.NET5内置依赖项注入中设置上述内容

我目前有以下情况:

(新的不起作用)4

services.AddSingleton(s=>
新的ApiConnection(Configuration.GetSection(“地址”)
.GetSection(“webServiceRootAddress”).Value);
(新)5

services.addScope();

但是上面所说的是将2个参数传递到构造函数中。如何在此处仅定义一个要传递的构造函数参数,因为HttpMessageHandler参数将通过依赖项注入传递(第5行)。

有几个选项,这里有几个选项

  • 使用
    s
    参数获取服务:

    services.AddSingleton<IApiConnection, ApiConnection>(s => 
    {
        var rootAddress = Configuration.GetSection("Address")
            .GetSection("webServiceRootAddress")
            .Value;
        var messageHandler = s.GetRequiredService<HttpMessageHandler>();
        return new ApiConnection(messageHandler, rootAddress );
    });
    
    将服务添加到DI容器:

    services.Configure<MyConfig>(Configuration.GetSection("Address")
        .GetSection("webServiceRootAddress"));
    

  • 太棒了,谢谢!
    services.AddSingleton<IApiConnection, ApiConnection>(s =>
        new ApiConnection(Configuration.GetSection("Address")
            .GetSection("webServiceRootAddress").Value));
    
    services.AddScoped<HttpMessageHandler, HttpClientHandler>();
    
    services.AddSingleton<IApiConnection, ApiConnection>(s => 
    {
        var rootAddress = Configuration.GetSection("Address")
            .GetSection("webServiceRootAddress")
            .Value;
        var messageHandler = s.GetRequiredService<HttpMessageHandler>();
        return new ApiConnection(messageHandler, rootAddress );
    });
    
    public class MyConfig
    {
        public string WebServiceRootAddress { get; set; }
    }
    
    services.Configure<MyConfig>(Configuration.GetSection("Address")
        .GetSection("webServiceRootAddress"));
    
    public ApiConnection(HttpMessageHandler messageHandler, MyConfig myConfig)
    {
        var webServiceRootAddress = myConfig.WebServiceRootAddress;
    }