![](/img/trans.png)
[英]How to get an instance of an injected service without constructor injection in .NET Core?
[英]how to implement Open Generic Constructor Injection in Dot Net Core
我有一个审计日志接口:
public interface IAuditDbContext<T1, T2>
{
T1 AuditLog { get; set; }
T2 ChangeTracker { get; }
}
现在在主 AppDbContext 接口中,我将其继承为:
public interface IAppDBContext<T1, T2> : IAuditDbContext<T1,T2>
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
在主 AppDbContext 类中,我继承为:
public class AppDBContext : DbContext, IAppDBContext<DbSet<Audit>, ChangeTracker>
{
....
}
问题是,在依赖注入时,我试图注入它:
services.AddScoped(
typeof(IAppDBContext<,>),
typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext)));
我也尝试过其他方法,但无法成功 - 我收到的一些错误消息是:
错误信息:
- Message=提供的泛型参数的数量不等于泛型类型定义的数量。
- 无法实例化实现类型“Common.Application.Interfaces”。 IAuditDbContext
2[T1,T2]' for service type 'Common.Application.Interfaces.IAppDBContext
2[T1,T2]'
请求帮助以正确实施它。
typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext))
IAuditDbContext
接口中有两个泛型参数,因此需要为MakeGenericType
方法提供两个参数。
但是,我不确定它是否是您所需要的。 您应该将接口映射到一些可能启动的类,而不是接口。
services.AddScoped(typeof(IAppDBContext<,>), typeof(AppDBContext)); //example
但是你真的需要注册开放泛型类型吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.