问题描述
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
但是,您真的需要注册开放的通用类型吗?