简体   繁体   中英

ASP.Net Core DI Factory Based on HttpContext

I want the ASP.Net Core IoC container to provide an implementation of an interface based on what view is currently being shown. I figured that I should be able to do this at run time by providing a factory method. In Startup.cs I have added the following registration:

services.AddTransient<IMyInterface>(serviceProvider => 
{
    var context = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;

    //Need to switch on current view somehow?
    switch(context.??????){
        case ???:
             return new MyImplementationOne();
        case ???:
             return new MyImplementationTwo():

    }

}

How can I use HttpContext to switch based on the current view being shown? Or, should I be using some other service available through the serviceProvider ?

Usually you would register a 'Factory' in your DI Container, for example IWhateverServiceFactory...

This would have a method, that takes in the View name (which you can get from the RouteContext) and returns the relevant implementation. This way you can change the logic as to which implementation easily, if for example at some point in the future you want to use a generic implementation.

public interface IWhateverServiceFactory{
    IService GetService(String currentViewName);
}

public class DefaultWhateverServiceFactory : IWhateverServiceFactory{
    IService GetService(String currentViewName){
        switch(currentViewName){
        case ???:
             return new MyImplementationOne();
        case ???:
             return new MyImplementationTwo():
        }
    }
}

Of the RouteContext doesn't work for you, you can use something like;

System.IO.Path.GetFileNameWithoutExtension(
            ((RazorView)html.ViewContext.View).ViewPath
        );

If you are using Razor to get the views name, or

Html.ViewContext.RouteData.GetRequiredString("action");

to get the action name...

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