Transient – A new instance of the service is created each time it is requested. It can be used for stateless and light weight services.
可以理解为每次都要创建,主要针对状态无关、轻量级的服务。
Scoped – A single instance is created once per request.
每次HttpRequest就创建一次,HttpRequest以内就不用创建了;下一次HttpRequest的话要重新创建。
Singleton – Created only once the first time they are requested.
应用程序内只创建一次。
玩过Autofac的同学发现这个其实和Autofac是一样的。
Ref:http://www.c-sharpcorner.com/article/dependency-injection-in-Asp-Net-core/
Startup的ConfigureServices主要用于依赖注入的配置
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<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<FruitServices>();
}