Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Net Core Dependency Injection for Non-Controller

Tags:

Seems crazy that something like this is causing me such a headache. But here it is:

How do you use the built-in dependency injection for net core for a non-controller class? Please provide an example with includes instantiation.

Thanks.

like image 450
CCPony Avatar asked Jan 12 '17 13:01

CCPony


People also ask

Does .NET Core have dependency injection?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

How does dependency injection work .NET Core?

Dependency Injection is the design pattern that helps us to create an application which loosely coupled. This means that objects should only have those dependencies that are required to complete tasks.

How many types of dependency injection are there in ASP.NET Core?

NET Core provides three kinds of dependency injection, based in your lifetimes: Transient: services that will be created each time they are requested. Scoped: services that will be created once per client request (connection) Singleton: services that will be created only at the first time they are requested.


1 Answers

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; } 
like image 71
John Arundell Avatar answered Sep 18 '22 22:09

John Arundell