ASPNET5 Dependency Injection (Dependency injection)

Source: Internet
Author: User
Tags hosting

Dependency injection has always been an integral part of the ASP (Web Api,signalr and MVC), but in the past, this framework has been upgraded and has its own dependency injection implementation, even though the Katana project wants to connect these projects through Owin. You still have to do a unified container to support them, and things are changing now. AbstractThe ASP. NET team decided to provide dependency injection by refining the core features of the most popular IOC containers and then having different components implement those interfaces to implement dependency injection. IServiceProviderThis most important interface, development can be through this interface to retrieve the IOC container has registered services, this interface has only one method: GetService (Type), similar to those in Aotufact. container.resolve<service>, or in the Ninject. kernel.get<service>.All middleware have two ways to get what you want. IServiceProvider.
    • Application level: Provided to middleware via the httpcontext.applicationservices property
    • Request level-provided to middleware through the httpcontext.requestservices attribute, the serviceprovider of this range is created through an implicit middleware in the first request management channel is released before the request finally returns a response.
All middleware can resolve their services through these attributes, such as the ASP. NET MVC Middleware requestservicesTo create controllers and their dependencies. Iservicescope  This interface is a wrapper for the container, and the main function is to release the container after the request is over.
    • IServiceProvider
    • Dispose ()
  iservicescopefactoryVery simple one interface, only one return IservicescopeThe method Createservicescope ()  So if you need to implement an IOC container, you will have to implement the above interface yourself. Servicelifetime
    • Singleton A single instance throughout the application
    • Scoped A single instance within the scope window
ServicedescriptorDescription of the registration service,
    • servicetype is used to replace the interface of a specific implementation class, type
    • Implementationtype The specific implementation type of the above interface, type
    • The life cycle of Lifetime Services, singleon,scoped or Transient
    • implementaionfactory type func<iserviceprovider,object> In some scenarios, developers want to provide a factory method to create a concrete implementation class. They are independent of each other, if you provide the implementationtype, that can not provide impletentaionfactory.
    • implementationinstance Concrete Examples
registering Services Register your service now, ASPNET5 hope your StartupThere is a name in the class configureservicesMethod name, with a series of servicedescriptorsParcel in iservicecollection, and nothing is returned. All you need to do is create a series of Servicedescriptorand add them to the collection, and the Web application will load them later and register them in the container
publicvoidconfigureservices (iservicecollection services) {    var servicedescriptor = Newservicedescriptor (typeoftypeof(Bankmanager), servicelifetime.transient);    Services. ADD (servicedescriptor);      // ADD MVC Services to the Services container.     Services. Addmvc ();}

Notes creating servicedescriptor is a bit tedious, and that's what you see some middleware using extension methods to create servicedescriptors, like "service." ADDMVC () "  The following pseudo-statement describes how service initiation and serviceprovider are created, and the corresponding code can be Hostingengine.startTo find out how the application started.
    1. Hosting engine creates a iservicecollection, which is a collection object of Servicedescriptor
    2. Hosting engine will add all the services it needs
    3. Hosting engine will confirm that there is a Startup class in the assembly, and there is a configureservices method
    4. Hosting engine will go to load this method and pass iservicecollection
    5. The configureserivces in the Startup class adds the services required by the application to the collection
    6. Hosting engine will then create the defaultserviceprovider(ICO container) and register the services in iservicecollection in the service collection
    7. Hosting engine creates an application builder (Iapplicationbuilder) and assigns a iapplicationbuilder.applicationservices a new service Provider to the and use it further.
    8. Hosting Engin will create a requestservicescontainermiddleware middleware before Startup.configuer executes, and I'll introduce it later
    9. Hosting Engine executes the Configure method in the Startup class and passes application Builder to create the middleware. If service provider is required, the middleware can be created through the ApplicationServices attribute.
  Run the request

When the first request comes in, HttpContext will be created and passed to the Invokde method in the first middleware, and will be uploaded to the entire middleware. But before processing the first middleware, application Builder's The service Provider will be assigned to Httpcontext.applicationservices to ensure that the entire middleware can get the required services through this property, but you should remember that this is an application-level service provider, And depending on the IOC container of your choice, if you use it, your object may remain in the entire life cycle of your application.

Note: In theory, theoretically, as an application developer, you should not go directly to the service provider, if you want to use the Services Locator mode  

Well, this is an application-level service provider, and is there a service provider in the scope of each request?


In the 8th step listed above, we mentioned that hosting engine will create a RequestservicescontainermiddlewareMiddleware and will be the first time to execute it public async Task Invoke(HttpContext httpContext) {      using ( var container = RequestServicesContainer.EnsureRequestServices(httpContext, _services))      {          await _next.Invoke(httpContext);      } }
back in the request execution above, the service creates the HttpContext and assigns it to the Application-level service provider to Httpcontext.applicationservices, The first middleware is then called, which is the requestservicescontainermiddleware, and what it does is create a service provider in scope and destroy it at the end of the request.Its pseudo-implementation is:
    1. Request is being processed by Requestservicecontainermiddleware
    2. The Invoke method creates a iservicescopefactory through the Application-level Service provider.
    3. Iservicescopefactory creates a scope container (scoped container)
    4. Scoped container will be assigned to the attribute httpcontext.requestservices
    5. The Invoke method invokes the next middleware
    6. When all the middleware are executed and returned to the requestservicecontainermiddleware,scoped Container will be destroyed through the "using"
Note: Requestservicescontainermiddleware is to manage the creation and destruction of scoped Service through this packaging/help class Requestservicescontainer Provider.Httpcontext.requestservices is the scope service provider for the request lifecycle, and all subsequent middle can access it, for example, if you look at Mvcroutehandler.invokeactionasync you will find that it is through this to create C Ontroller's private async Task InvokeActionAsync(RouteContext context, ActionDescriptor actionDescriptor) {      var services = context.HttpContext.RequestServices;      Debug.Assert(services !=  null );      var actionContext =  new ActionContext(context.HttpContext, context.RouteData, actionDescriptor);      var optionsAccessor = services.GetRequiredService<IOptions<MvcOptions>>();      actionContext.ModelState.MaxAllowedErrors = optionsAccessor.Options.MaxModelValidationErrors;      var contextAccessor = services.GetRequiredService<IScopedInstance<ActionContext>>();      contextAccessor.Value = actionContext;      var invokerFactory = services.GetRequiredService<IActionInvokerFactory>();      var invoker = invokerFactory.CreateInvoker(actionContext);      if (invoker ==  null )      {          LogActionSelection(actionSelected:  true , actionInvoked:  false , handled: context.IsHandled);          throw new InvalidOperationException(              Resources.FormatActionInvokerFactory_CouldNotCreateInvoker(                  actionDescriptor.DisplayName));      }      await invoker.InvokeAsync(); } Note: 以一次提醒, 你不需要直接去使用Service Provider; 通过构造函数去创建服务,避免Service Locator模式。

ASPNET5 Dependency Injection (Dependency injection)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.