简体   繁体   中英

Pass in one argument to constructor of dependency injection class, that will also have a dependency injected argument

I am converting .net framework to .net 5.0 and using the built in dependency injection in .net 5.0 instead of Ninject library I used in .net framework.

I have the following constructor that takes in a messageHandler (through dependency injection) as well as a web service root address:

(old) 1.

public ApiConnection(HttpMessageHandler messageHandler, string webServiceRootAddress)

Here is the setup for the dependency injection through ninject in .net framework:

(old) 2.

kernel.Bind<IApiConnection>().To<ApiConnection>().InSingletonScope()
    .WithConstructorArgument(
        "webServiceRootAddress",
        ConfigurationManager.AppSettings["webServiceRootAddress"]);

(old) 3.

kernel.Bind<HttpMessageHandler>().To<HttpClientHandler>();

I want to set up the above in the built in dependency injection in .net 5 within the Startup file.

I currently have the following:

(new doesn't work) 4.

services.AddSingleton<IApiConnection, ApiConnection>(s =>
    new ApiConnection(Configuration.GetSection("Address")
        .GetSection("webServiceRootAddress").Value));

(new) 5.

services.AddScoped<HttpMessageHandler, HttpClientHandler>();

But the above is expecting 2 arguments to be passed into the constructor. How do I define only one constructor argument to be passed in here, because the HttpMessageHandler argument will be passed in through dependency injection (line 5).

There's a few options, here's a couple of them.

  1. Use the s parameter to get the service:

     services.AddSingleton<IApiConnection, ApiConnection>(s => { var rootAddress = Configuration.GetSection("Address").GetSection("webServiceRootAddress").Value; var messageHandler = s.GetRequiredService<HttpMessageHandler>(); return new ApiConnection(messageHandler, rootAddress ); });
  2. Pass in a service/class that gets the root address:

     public class MyConfig { public string WebServiceRootAddress { get; set; } }

    Add the service to your DI container:

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

    Now modify your ApiConnection service to take the class instead of the string:

     public ApiConnection(HttpMessageHandler messageHandler, MyConfig myConfig) { var webServiceRootAddress = myConfig.WebServiceRootAddress; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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