zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    2020年,初级、中级 Android 工程师可能因离职而失业吗?
    Android 后台运行白名单,优雅实现保活
    使用DataBinding还在为数据处理头疼?这篇文章帮你解决问题
    Android 7.x Toast BadTokenException处理
    2017-2020历年字节跳动Android面试真题解析(累计下载1082万次,持续更新中)
    Flutter 尺寸限制类容器总结:这可能是全网解析最全的一篇文章,没有之一!
    并行收集器
    高性能索引策略
    Innodb简介
    索引的优点
  • 原文地址:https://www.cnblogs.com/MingQiu/p/8398400.html
Copyright © 2011-2022 走看看