Answer the question
In order to leave comments, you need to log in
How to correctly set up DI?
I'm developing a class structure for my project and I've run into a problem.
I have a WebHelper class, which is essentially a layer between HttpClient and my various services. As a dependency, it takes the HttpClientFactory factory, which, in turn, can return the clients I need. This is done with the intent that both an empty HttpClient and one containing an AuthorizationToken or other Headers may be required. Thus, there is a service that communicates with a third-party data source and needs a token, and there are also a couple of services that do not require anything.
Schematically, all this can be depicted as follows:
ApplicationSolution
Application.Site
Startup (регистрация объектов происходит здесь)
Application.Core
WebHelper
HttpClientFactory
Application.Service1 (требующий Headers в HttpClient)
Application.Service2 (использует чистый HttpClient)
public void ConfigureServices(IServiceCollection services)
{
services.AddService1(Configuration);
services.AddService2(Configuration);
services.AddMvc();
}
public static IServiceCollection AddSerivce1(this IServiceCollection services, IConfigurationRoot configuration)
{
services.AddSingleton<IHttpClientFactory, HttpClientFactory>(service =>
{
var factory = new HttpClientFactory
{
Method = () =>
{
var jsonType = new MediaTypeWithQualityHeaderValue("application/json");
var authorizationHeader = new AuthenticationHeaderValue("Basic", token);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(jsonType);
httpClient.DefaultRequestHeaders.Authorization = authorizationHeader;
return httpClient;
}
};
return factory;
});
services.AddSingleton<IWebHelper, WebHelper>();
...
return services;
}
public static IServiceCollection AddService2(this IServiceCollection services, IConfigurationRoot configuration)
{
services.AddSingleton<IHttpClientFactory, HttpClientFactory>(
service => new HttpClientFactory {Method = () => new HttpClient()});
services.AddSingleton<IWebHelper, WebHelper>();
...
return services;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question