【发布时间】:2020-08-01 11:27:14
【问题描述】:
我有一个自定义服务,我使用的是 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);
【问题讨论】:
-
services.AddDataProtection();? -
@viveknuna 我有几个服务,因为我没有一一添加
-
@GuruStron 没用 :(
-
@GuruStron 是的,你是对的,我误解了这个问题
-
@user13409315 还没有解决?可以加minimal reproducible example吗?
标签: c# asp.net-core dependency-injection