Search code examples
c#asp.net-coredependency-injection

Unable to resolve service for type 'Microsoft.AspNetCore.DataProtection.IDataProtector'


I have a custom service which in that I'm using Microsoft's IDataProtector. I have registered my service in startup with AddScoped but i have a problem with using IDataProtector.

error message:

Unable to resolve service for type 'Microsoft.AspNetCore.DataProtection.IDataProtector' while attempting to activate 'Service'.

here is my code :

public class Service: IInjectable
{
    private readonly IDataProtector _protector;
     
    public Service(IDataProtector protector)
    {
      _protector = protector.CreateProtector("key");
    }

    other code ...
}

The way I have registered my service:

    public static void RegisterScoped<T>(
        this IServiceCollection services, params Assembly[] assemblies)
    {
        IEnumerable<Type> types = assemblies.SelectMany(a => a.GetExportedTypes())
            .Where(c => c.IsClass && typeof(T).IsAssignableFrom(c));

        foreach (var item in types)
            services.AddScoped(item);
    }

StartUp :

 services.RegisterScoped<IInjectable>(typeof(IInjectable).Assembly);

Solution

  • Finally , i found the problem :

    i had to use IDataProtectionProvider instead of IDataProtector in my service constructor