本文介绍了没有修改闭包的ASP.NET Core MvcOptions依赖项注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的ASP.NET Core项目中,我目前将 IFilterMetadata
依赖项注入到<$ c $中的 MvcOptions
中$ c> ConfigureServices 方法,方法如下:
In my ASP.NET Core project, I currently inject an IFilterMetadata
dependency into MvcOptions
in the ConfigureServices
method in the following way:
public override IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddProjectSpecificStuff();
IExceptionFilter exceptionFilter = null;
services.AddMvc(options => { options.Filters.Add(exceptionFilter); });
var provider = base.ConfigureServices(services);
exceptionFilter = provider.GetService<IExceptionFilter>();
return provider;
}
此方法有效,但导致诸如ReSharper之类的代码分析器抱怨对已修改内容的访问
This works, but causes code analyzers such as ReSharper to complain about access to modified closure.
是否有另一种方法可以在不使用修改的闭包的情况下实现相同的依赖注入?
Is there an alternative to achieve the same dependency injection without using modified closure?
推荐答案
当过滤器具有依赖项时,只需向通用add方法注册它们,而不要传递实例。
When your filters have dependencies, just register them with the generic add method instead of passing an instance.
services.AddMvc(options =>
{
options.Filters.AddService(typeof(IExceptionFilter));
// ASP.NET Core 2.0
//options.Filters.AddService<IExceptionFilter>();
});
这篇关于没有修改闭包的ASP.NET Core MvcOptions依赖项注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!