Search code examples
c#dependency-injectionasp.net-core-2.0service-locator

Asp.net Core 2 - How to use ServiceLocator in Asp.net Core 2.0


My Startup is like this :

public void ConfigureServices(IServiceCollection services)
{
    // code here 
    Bootstraper.Setup(services);
}

And my Bootstraper class is like this :

public static partial class Bootstraper
{
    // code here 
    public static IServiceCollection CurrentServiceCollection { get;set;}

    public static IServiceProvider CurrentServiceProvider
    {
        get { return CurrentServiceCollection.BuildServiceProvider(); }
    }    

    public static void Setup(IServiceCollection serviceCollection)
    {
        // code here 
        SetupLog();
        InitializeCulture();
        InitializeDbContexts();
        RegisterDataModelRepositories();
    }

and this is content of my RegisterDataModelRepositories():

CurrentServiceCollection.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
CurrentServiceCollection.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));

in short : I just want to be able to use Service Locator in my methods without resolving dependency in class constructor ... is there any way around it ....


Solution

  • Dependency injection can also be done on a by action basis.

    Referece Dependency injection into controllers: Action Injection with FromServices

    Sometimes you don't need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]

    public IActionResult SomeAction([FromServices] IReportService reports) {
        //...use the report service for this action only
    
        return View();
    }
    

    Just make sure that the required services are registered with the service collection.

    services.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
    services.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
    services.AddTransient<IReportService, ReportService>().