ASP.NET Core MvcOptions dependency injection witho

2019-09-17 11:28发布

问题:

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:

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