Dependency injection of multiple instances of same type in ASP.NET Core 2

后端 未结 4 762
醉梦人生
醉梦人生 2020-12-29 23:57

In ASP.NET Core 2 Web Api, I want to use dependency injection to inject httpClientA instance of HttpClient to ControllerA, and an inst

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 00:51

    Really the consumer of the service should not care where about the implementation of the instance it is using. In your case I see no reason to manually register many different instances of HttpClient. You could register the type once and any consuming instance that needs an instance will get it's own instance of HttpClient. You can do that with AddTransient.

    The AddTransient method is used to map abstract types to concrete services that are instantiated separately for every object that requires it

    services.AddTransient();
    

提交回复
热议问题