Home > Software engineering >  Error injecting two dependencies Iconfiguration and IMemoryCache in service from Startup net core
Error injecting two dependencies Iconfiguration and IMemoryCache in service from Startup net core

Time:12-18

I'm trying to use IMemoryCache in a service than used Iconfiguration, but actually i dont know the correct way to inject in the constructor.

The service:

 public class AuthService: IAuthService
 {
    private readonly IConfiguration _configuration;
    private readonly IMemoryCache _cache;

    public AuthService(IConfiguration configuration, IMemoryCache cache)
    {
        _configuration= configuration;
        _cache = cache;
    }
 }

*Inject like singleton way in Startup (Error: Generate error when consume any controller with that service):

  services.AddMemoryCache();
  services.AddSingleton<AuthService>();

*Inject creating class Service in Startup (Error: needs IMemoryCache on constructor)

services.AddMemoryCache();
services.AddSingleton<IAuthService>(
         new AuthService(Configuration)
);

What is the correct way to inject IMemoryCache into AuthService from Startup class?

CodePudding user response:

services.AddMemoryCache() will register an instance as a singleton, meaning that there are no mismatched lifecycles.

In addition, there is no need to manually specify a factory. As Jesse mentioned above, register both your interface and concrete class and the Dependency Injection framework will provide both dependencies to your service:

services.AddSingleton<IAuthService, AuthService>();
  • Related