1.创建一个服务

public interface IGreetingService
{
    string Greet(string to);
}

public class GreetingService : IGreetingService
{
    public string Greet(string to)
    {
        return $"Hello {to}";
    }
}

2.然后可以在需要的时候注入,下面将此服务注入一个中间件(Middleware)

public class HelloWorldMiddleware
{
    private readonly RequestDelegate _next;

    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, IGreetingService greetingService)
    {
        var message = greetingService.Greet("World (via DI)");
        await context.Response.WriteAsync(message);
    }
}

3.使用此中间件的扩展方法(IApplicationBuilder)

public static class UseMiddlewareExtensions
{
    public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder app)
    {
        return app.UseMiddleware<HelloWorldMiddleware>();
    }
}

4.下面需要将此服务添加到ASP.NET Core的服务容器中,位于Startup.cs文件的ConfigureServices()方法

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IGreetingService, GreetingService>();
}
public void ConfigureServices(IServiceCollection services)
        {
            //.NET Core DI 为我们提供的实例生命周期包括三种
            //var serviceCollection = new ServiceCollection()
            //.AddTransient<IPhone, WinPhone>();              //每一次GetService都会创建一个新的实例
            //.AddSingleton<IPhone, ApplePhone>()             //在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内)
            //.AddScoped<IGreetingService, GreetingService>();//整个应用程序生命周期以内只创建一个实例
            services.AddMvc();
        }

 

5.然后在请求管道中(request pipeline)使用此中间件,位于Startup.cs文件的Configure()方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHelloWorld();
}

如果在mvc中使用可以忽略2,3,5步

 原文地址:http://www.cnblogs.com/sanshi/p/7705617.html

相关文章:

  • 2021-11-12
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-02-21
  • 2023-02-24
  • 2019-01-08
猜你喜欢
  • 2022-01-27
  • 2021-09-17
  • 2021-09-13
  • 2021-07-28
  • 2020-05-19
  • 2019-05-22
相关资源
相似解决方案