【发布时间】:2020-08-17 21:06:31
【问题描述】:
我正在通过复数站点视频学习 ASP.NET 核心。视频中的小伙伴告诉我,我可以通过在 Startup.ConfigureServices 中注册来将“服务”添加为单例或瞬态。
public class Startup {
public Startup() {
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
// Register the Greeter as an IGreeter and have the ASP.NET framework register it to be available to anyone who wants an IGreeter
// Dependency injection?
services.AddSingleton<IGreeter, Greeter>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IGreeter greeter) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.Run(async (context) => {
var greeting = greeter.GetGreeting();
await context.Response.WriteAsync(greeting);
});
}
}
他不太清楚是谁在实例化它,它的生命周期是什么,以及它在哪里可用。有人可以帮我填写这些详细信息吗?
这是否与我使用 Autofac 之类的依赖注入框架所做的一样,但 ASP.NET Core 已经内置了它?或者这有什么不同?
【问题讨论】:
标签: c# asp.net-core dependency-injection