简体   繁体   中英

ASP.NET Core MvcOptions dependency injection without modified closure?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM