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

  • 相关阅读:
    错排问题
    用GDAL/OGR去读shapefile
    聊聊MyBatis缓存机制
    一份平民化的应用性能优化检查列表(完整篇)--转
    微服务实战(七):从单体式架构迁移到微服务架构
    微服务实战(六):选择微服务部署策略
    微服务实战(五):微服务的事件驱动数据管理
    微服务实战(四):服务发现的可行方案以及实践案例
    微服务实战(三):深入微服务架构的进程间通信
    微服务实战(一):微服务架构的优势与不足
  • 原文地址:https://www.cnblogs.com/MingQiu/p/8398400.html
Copyright © 2011-2022 走看看