【发布时间】:2020-01-14 01:11:57
【问题描述】:
我正在使用 ASP.net Core MVC 2.2 开发一个 Web 应用程序,并且在我的 Startup 类中我注册了一个 MyService 类型的依赖注入,如下所示:
public void ConfigureServices(IServiceCollection services)
{
//Inject dependency
services.AddSingleton<MyService>();
//...other stuff...
}
这可以正常工作。但是,我需要在应用程序关闭期间检索MyService 的实例,以便在应用程序终止之前执行一些清理操作。
所以我尝试这样做——首先我在我的启动类中注入了IServiceProvider,所以它是可用的:
public Startup(IConfiguration configuration, IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
Configuration = configuration;
}
然后,在 Configure 方法中,我为ApplicationStopping 事件配置了一个钩子,以拦截关机并调用OnShutdown 方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime)
{
//Register app termination event hook
applicationLifetime.ApplicationStopping.Register(OnShutdown);
//...do stuff...
}
最后,在我的 OnShutdown 方法中,我尝试获取我的依赖项并使用它:
private void OnShutdown()
{
var myService = ServiceProvider.GetService<MyService>();
myService.DoSomething(); //NullReference exception, myService is null!
}
但是,正如您从代码中的注释中看到的那样,这不起作用:返回的依赖项始终为 null。我在这里做错了什么?
【问题讨论】:
标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-2.2