ASP.NET Core MvcOptions dependency injection witho

2019-09-17 11:00发布

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;
}

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?

1条回答
Fickle 薄情
2楼-- · 2019-09-17 11:47

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>();
});
查看更多
登录 后发表回答