Net Core Dependency Injection for Non-Controller

You can easily define a static class with one property like:

public static class StaticServiceProvider
{
    public static IServiceProvider Provider { get; set; }    
}

after defined class you have to scope the service in the Startup.ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    //TODO: ...

    services.AddScoped<IUnitOfWork, HttpUnitOfWork>();            
    services.AddSingleton<ISomeInterface, ISomeImplementation>();
}

then inside the Startup.Configure method on startup you can set the provider as static class property:

public void Configure(IApplicationBuilder app, ...)
{
    StaticServiceProvider.Provider = app.ApplicationServices;

    //TODO: ...
}

Now you can easily call StaticServiceProvider.Provider.GetService method almost everywhere in your application:

var unitOfWork = (IUnitOfWork)StaticServiceProvider.Provider.GetService(typeof(IUnitOfWork));

Just make the class a service.

In startup.cs

services.AddScoped<AccountBusinessLayer>();

Then in controller, same as you do for other services:

private readonly AccountBusinessLayer _ABL;

Include in constructor as you do for other services:

 public AccountController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager,IOptions<IdentityCookieOptions> identityCookieOptions,
    IEmailSender emailSender,
    ISmsSender smsSender,
    ILoggerFactory loggerFactory,
    RoleManager<IdentityRole> roleManager,
    AccountBusinessLayer ABL
  )
{
  _userManager = userManager;
  _signInManager = signInManager;
  _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
  _emailSender = emailSender;
  _smsSender = smsSender;
  _logger = loggerFactory.CreateLogger<AccountController>();
  _roleManager = roleManager;
  _ABL = ABL;
}

Leave a Comment