dir.by  
  Поиск  
Компьютер, программы
.NET Core
 Встроенный контейнер IoC в ASP.NET Core 
посмотрели 9027 раз
обновлено: 13 March 2019
ASP.NET Core уже имеет встроенный контейнер внедрения зависимостей, который представлен интерфейсом IServiceProvider
Шаг 1
За установку сервисов в приложении отвечает метод ConfigureServices, определенный в классе Startup.
  C#     файл Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Services;

namespace WebApplication1
{
     public class Startup
     {
          // This method gets called by the runtime. Use this method to add services to the container.
          // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
          public void ConfigureServices(IServiceCollection services)
          {
               services.AddMvc();
               services.AddSingleton<IMyServ1, MyServ1>();
          }

          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
               if (env.IsDevelopment())
               {
                    app.UseDeveloperExceptionPage();
               }

               app.UseMvcWithDefaultRoute();
          }
     }
}
Шаг 2 типы
Сервисы, которые создаются механизмом Depedency Injection, могут представлять один из следующих типов:
services.AddTransient<...>();
при каждом обращении к сервису создается новый объект сервиса. В течение одного запроса может быть несколько обращений к сервису, соответственно при каждом обращении будет создаваться новый объект. Подобная модель жизненного цикла наиболее подходит для легковесных сервисов, которые не хранят данных о состоянии
services.AddScoped<...>();
для каждого запроса создается свой объект сервиса. То есть если в течение одного запроса есть несколько обращений к одному сервису, то при всех этих обращениях будет использоваться один и тот же объект сервиса.
services.AddSingleton<...>();
объект сервиса создается при первом обращении к нему, все последующие запросы используют один и тот же ранее созданный объект сервиса
Шаг 3 Передача зависимостей в контроллер
Как и любой класс, контроллер может получать сервисы приложения через механизм dependency injection.
В контроллере это можно делать следующими способами:
Через конструктор
Через параметр метода, к которому применяется атрибут FromServices
  C#  
public string Index([FromServices] ITimeService timeService)
{
return timeService.Time;
}
Через свойство HttpContext.RequestServices
  C#  
public string Index()
{
     ITimeService timeService = (ITimeService)HttpContext.RequestServices.GetService(typeof(ITimeService));
     return timeService?.Time;
}
Шаг 4 получить добавленные в приложения сервисы различными способами;
Через конструктор класса (за исключением конструктора класса Startup)
Через параметр метода Configure класса Startup
  C#  
public class Startup
{
     public void ConfigureServices(IServiceCollection services)
     {
          services.AddTransient<IMessageSender, EmailMessageSender>();
     }

     // Получаем зависимость IMessageSender
     public void Configure(IApplicationBuilder app, IMessageSender sender)
     {
          app.Run(async (context) =>
          {
               await context.Response.WriteAsync(sender.Send());
          });
     }
}
используя services.BuildServiceProvider
в методе ConfigureServices
класса Startup
  C#  
public void ConfigureServices(IServiceCollection services)
{
     ...

     // get service provider
     IServiceProvider serviceProvider = services.BuildServiceProvider();

     // get service
     IMessageSender messageSender = (IMessageSender)serviceProvider.GetService(typeof(IMessageSender));

     ...
}
Через параметр метода Invoke компонента middleware
  C#  
public class MessageMiddleware
{
     private readonly RequestDelegate _next;

     public MessageMiddleware(RequestDelegate next)
     {
          this._next = next;
     }

     public async Task Invoke(HttpContext context, IMessageSender messageSender)
     {
          context.Response.ContentType = "text/html;charset=utf-8";
          await context.Response.WriteAsync(messageSender.Send());
     }
}
Через свойство RequestServices контекста запроса HttpContext в компонентах middleware
IMessageSender messageSender = context.RequestServices.GetService();
Через свойство ApplicationServices объекта IApplicationBuilder в классе Startup
  C#  

public void Configure(IApplicationBuilder app)
{
     app.Run(async (context) =>
     {
          IMessageSender messageSender = (IMessageSender)app.ApplicationServices.GetService(typeof(IMessageSender));
          context.Response.ContentType = "text/html;charset=utf-8";
          await context.Response.WriteAsync(messageSender.Send());
     });
}
 
← Previous topic
Creating a new application ASP.NET Core MVC
 
Next topic →
Entity Framework in the ASP.NET Core MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is .NET Core?
Creating a New .NET Core Console App
ASP.NET Core
What is ASP.NET Core?
Creating a new application ASP.NET Core
ASP.NET Core MVC
Creating a new application ASP.NET Core MVC
Built-in IoC container in ASP.NET Core
<BR>
Database (Entity Framework) in ASP.NET Core MVC
Entity Framework in the ASP.NET Core MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
<BR>
Telerik (Kendo UI) in ASP.NET Core MVC
Telerik (Kendo UI) in ASP.NET Core MVC (connect Kendo js files using NPM and Webpack)
<BR>
Authentication (login/register/logout) in the ASP.NET Core MVC application
Authentication is login/register/logout in the ASP.NET Core MVC application
Additional topics, questions
Install a new version (.NET 9) for Visual Studio 2022 | Error: NETSDK1 The current .NET SDK does not support targeting .NET 9.0. Either target .NET 7.0 or lower, or use a version of the .NET SDK that supports .NET 9.0.
Install the new version (.NET 6.0) for Visual Studio 2022. Note! .NET 6.0 is not installed and does not work for Visual Studio 2019
Installing a new version (.NET Core 2.2) for Visual Studio 2019
Choosing between ASP.NET Core and ASP.NET?
Porting code to .NET Core from the .NET Framework
Error "unable to connect to web server "iis express" | ASP.NET Core | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET Core application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW sites for learning
Sites to learn ASP.NET Core

  Ваши вопросы присылайте по почте: info@dir.by