[Solved] How do I inject my own classes into controllers in ASP.NET MVC Core?


Classes that are injected with dependencies usually don’t use the concrete classes (UserManager.cs) for their constructor parameters, but rely on interfaces e.g. IUserManager. Although it is possible to use concrete classes, an interface provides looser coupling which is the reason for using dependency injection in the first place.

Whenever the framework encounters a constructor (in this case the constructor of the controller) that “wants” an interface it has too look up which concrete class it should use for injection.

Where

The relationship between “class wants type X” and “framework will inject it with type Y” is defined in the ConfigureServices method in Startup.cs.

What

1. Decide on the lifetime of the created object

There are three options for defining the above relationship, that differ in the lifetime the object created by the dependency injection framework is alive.

The official documentation says:

Transient

Transient lifetime services are created each time they are requested.
This lifetime works best for lightweight, stateless services.

Scoped

Scoped lifetime services are created once per request.

Singleton

Singleton lifetime services are created the first time they are
requested (or when ConfigureServices is run if you specify an instance
there) and then every subsequent request will use the same instance.

2. Add the code

After choosing a lifetime (scoped in the following examples) you add the line

services.AddScoped<IInterfaceUsedByControllerParameter, ClassThatWillBeInjected>();

or for OPs class

services.AddScoped<IUserManager, UserManager>();

or if UserManager implements several interfaces:

services.AddScoped<ILogin, UserManager>();
services.AddScoped<IRegister, UserManager>();

With those two lines whenever a class requires a constructor parameter with either of those two interfaces the dependency injection will provide it with an object of type UserManager.

Code examples

In case of the last example where UserManager implements the interfaces ILogin and IRegister:

Controler

public class UserController : Controller
    {
        private readonly ILogin    _login;
        private readonly IRegister _registration;

        public UserController(ILogin login, IRegister registration)
        {
            _login = login;
            _registration = registration;
        }
...
...
}

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddScoped<ILogin, UserManager>();
            services.AddScoped<IRegister, UserManager>();
            ...
            services.AddMvc();
            ...

1

solved How do I inject my own classes into controllers in ASP.NET MVC Core?