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

use*_*315 4 c# dependency-injection asp.net-core

我有一项自定义服务,其中我使用 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 ...
}
Run Code Online (Sandbox Code Playgroud)

我注册服务的方式:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

启动 :

 services.RegisterScoped<IInjectable>(typeof(IInjectable).Assembly);
Run Code Online (Sandbox Code Playgroud)

use*_*315 11

最后,我发现了问题:

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