• asp.net core 依赖注入


    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

  • 相关阅读:
    「BZOJ 1000」A+B Problem
    「HNOI 2008」越狱
    蓝桥杯 拼音字母
    蓝桥杯 抽签
    蓝桥杯 快速排序
    [蓝桥杯] 最大比例
    [蓝桥杯] 交换瓶子
    [蓝桥杯] 四平方和
    [蓝桥杯] 剪邮票
    [蓝桥杯] 方格填数
  • 原文地址:https://www.cnblogs.com/MingQiu/p/8398400.html
Copyright © 2020-2023  润新知