How in netcore, pleasant to use IServiceProvider

Before doing dotnet framework has been developed, using dependency injection Autofac, Autofac general usage is when the service starts, will use the interface implementation class name injected into it,

Then when the service elsewhere if you use the class directly in the Resolve Container inside out can be.

 

Later use netcore 2.0+, the framework itself uses a Microsoft.Extensions.DependencyInjection, is when the service starts, the need to inject a service by

public void ConfigureServices(IServiceCollection services)

Dependency injection, the service elsewhere in the constructor of the service instance out, and then call a specific method to achieve.

 

At the beginning, because the scene is relatively simple, using them more comfortable, and later with the business complex, is facing a number of challenges:

1) In a method of service, we do not want the constructor, and now want to use the interface method has been injected into the country?

To solve this problem, we introduced IHttpContextAccessor (web services), there HttpContext in IHttpContextAccessor inside,

In HttpContext which has a RequestServices is IServiceProvider type, which has been injected into the service of what we want:

 public abstract class ControllerBase : Controller
 {
    protected ControllerBase(IMediator mediator, ILogger logger, IHttpContextAccessor accessor)
     {
        var configuration = accessor.HttpContext.RequestServices.GetRequiredService<IConfigurationManager>();
     }
 }

 PS: using HttpContext inside RequestServices is limited, such as how to write unit tests? (In fact, imitation or web-initialization, this is not discussed)

RequestServices use HttpContext inside of the above solve some problems, but later encountered a problem

2) asynchronous programming, logic inside Handler process is relatively time-consuming, so we intend to use out of the inside of the logic asynchronously and returns the result immediately,

Immediately return result HttpContext.RequestServices becomes null, so use RequestServices place all logic error in the asynchronous call.

 

According to this, we increase ServiceLocator class in common projects which:

public class ServiceLocator
    {
        public static IServiceProvider Services { get; private set; }
        public static void SetServices(IServiceProvider services)
        {
            Services = services;
        }
    }

 Then public void ConfigureServices (IServiceCollection services)

 Methods which use

// inject in the global variable in maintenance 
 ServiceLocator.SetServices (serviceProvider);

 PS: Try to use this assignment in the bottom of the method.

Then another location in your service to use it to get the interface has been injected

 

 

 

Guess you like

Origin www.cnblogs.com/walt/p/11947464.html