无法解析类型为“ Microsoft.AspNetCore.DataProtection.IDataProtector”的服务

时间:2020-08-01 11:27:14

标签: c# asp.net-core dependency-injection

我有一个自定义服务,因为我正在使用Microsoft的IDataProtector。 我已经在AddScoped的启动中注册了服务,但是在使用IDataProtector时遇到了问题。

错误消息:

尝试激活“服务”时,无法解析类型为“ Microsoft.AspNetCore.DataProtection.IDataProtector”的服务。

这是我的代码:

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

    other code ...
}

我注册服务的方式:

    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);
    }

启动:

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

1 个答案:

答案 0 :(得分:1)

最后,我发现了问题:

我必须在服务构造函数中使用IDataProtectionProvider而不是IDataProtector