c# - IServiceCollection - 依赖注入?在哪里可用?
问题描述
我正在通过复数视频学习 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 内置了它吗?或者这有什么不同?
解决方案
谁在实例化它,它的生命周期是什么,以及它在哪里可用。
框架将使用您在 DI 容器中注册时指定的生命周期来实例化服务。您注册的所有服务都可以在包含您的 DI-Container 的主项目中引用的项目中使用。
这是在做我使用 Autofac 之类的依赖注入框架所做的事情,但是 ASP.NET Core 内置了它吗?或者这有什么不同?
一切都与其他 DI 容器相同,例如AutoFac
. DI 是使用名为Microsoft.Extensions.DependencyInjection的 ASP.NET Core 的内置 DI 容器完成的
推荐阅读
- c - 如何在子进程和父进程之间连续切换上下文?
- c++ - 尝试使用 C++ 中的锁进行捕获
- angular - 显示使用输入值将名称添加到列表的用户列表
- linux - 如何关闭 Net::LDAP::Server
- delphi - Firedac - Datasnap + FDMemtable + fkInternalCalc
- c# - LINQ 中的完全外部联接针对唯一键进行了优化
- hyperledger-fabric - Hyperledger Fabric vs Sawtooth vs Iroha vs Indy vs Burrow?它们有何不同?有哪些用例?
- neo4j - Neo4j - 将所有路径导出到 csv。每条路径一排
- laravel - 获取 Laravel Mix 以从不同路径转换 JS
- c++ - boost::property_tree 的通用枚举转换器