.NET Core ConfigureServices

节选自这里

ConfigureServices是Startup类中可以选择定义的一个方法,作用即实现了依赖注入(DI)的配置,只有把服务添加到服务容器中才能让这些服务可以通过依赖注入的形式在应用中使用。方法参数如下:

  • IServiceCollection:整个ASP.NET Core 默认带有依赖注入(DI),IServiceCollection是依赖注入的容器,首先创建一个类(Foo)和接口(IFoo),代码清单如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
   public interface IFoo
    {
        string GetFoo();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    public class Foo : IFoo
    {
        public string GetFoo()
        {
            return "foo";
        }
    }
}

在ConfigureServices 中将接口和实现注入至容器

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IFoo, Foo>();
}

如果想在每次Http请求后都使用IFoo的GetFoo()方法来处理,上面讲到可以在Configure方法中注册函数,在注册过程中由于使用了依赖注入(DI),因此可以直接通过 RequestServices.GetRequiredService<IFoo>() 泛型方法将IFoo对象在容器中取出。

app.Run((context) =>
{
       var str = context.RequestServices.GetRequiredService<IFoo>().GetFoo();
       return context.Response.WriteAsync(str);
});

除了自己的接口外,还支持通过扩展方法添加更多的注入方法,比如EntityFramework、mvc框架都实现自己的添加方法。

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();

    // Add application services.
     services.AddTransient<IFoo, Foo>();

}

 

posted @ 2018-02-22 11:03  双子牧场主  阅读(463)  评论(0编辑  收藏  举报