标签:
publicvoidConfigureServices(IServiceCollection services) { var serviceDescriptor = newServiceDescriptor(typeof(IBankManager), typeof(BankManager), ServiceLifetime.Transient); services.Add(serviceDescriptor); // Add MVC services to the services container. services.AddMvc(); }
备注: 创建serviceDescriptor有一些繁琐, 这就是你看到一些中间件用扩展方法去创建ServiceDescriptors, 像“service.AddMvc()”
当第一个请求过来时,Httpcontext会被创建并传给第一个Middleware中的Invokde方法中,并会一直传到整个Middleware.但是在处理第一个中间件之前,Application Builder ‘s Service Provider 会被分配到HttpContext.ApplicationServices,确保整个中间件都可以通过这个属性获得需要的服务,不过,你应该记住这是一个应用程序级别的服务提供者,并且依赖于你选择的Ioc容器,如果你使用了它,你的对象可能会一直驻留在应用程序整个生活周期中.
好吧,这是一个应用程序级别的服务提供者,那有没有每次请求范围里的的服务提供者?
publicasyncTask Invoke(HttpContext httpContext){ using(varcontainer = RequestServicesContainer.EnsureRequestServices(httpContext, _services)) { await_next.Invoke(httpContext); }}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)
标签:
原文地址:http://www.cnblogs.com/dillon/p/5143266.html