[英]how to implement Open Generic Constructor Injection in Dot Net Core
I have an interface for Audit Logging:我有一个审计日志接口:
public interface IAuditDbContext<T1, T2>
{
T1 AuditLog { get; set; }
T2 ChangeTracker { get; }
}
now in main AppDbContext interface, I am inheriting this as:现在在主 AppDbContext 接口中,我将其继承为:
public interface IAppDBContext<T1, T2> : IAuditDbContext<T1,T2>
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
and in main AppDbContext class, I am inheriting as:在主 AppDbContext 类中,我继承为:
public class AppDBContext : DbContext, IAppDBContext<DbSet<Audit>, ChangeTracker>
{
....
}
The problem is, at the time of Dependency Injection, I am trying to inject it like:问题是,在依赖注入时,我试图注入它:
services.AddScoped(
typeof(IAppDBContext<,>),
typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext)));
I have tried other ways as well, but not able to get the success - some error messages that I am getting are:我也尝试过其他方法,但无法成功 - 我收到的一些错误消息是:
Error Messages:错误信息:
- Message=The number of generic arguments provided doesn't equal the arity of the generic type definition.
Message=提供的泛型参数的数量不等于泛型类型定义的数量。
- Cannot instantiate implementation type 'Common.Application.Interfaces.
无法实例化实现类型“Common.Application.Interfaces”。 IAuditDbContext
2[T1,T2]' for service type 'Common.Application.Interfaces.IAppDBContext
2[T1,T2]'IAuditDbContext
2[T1,T2]' for service type 'Common.Application.Interfaces.IAppDBContext
2[T1,T2]'
Requesting help to implement it correctly.请求帮助以正确实施它。
typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext))
typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext))
You have two generic parameters in IAuditDbContext
interface, so you need to provide two parameters for MakeGenericType
method. IAuditDbContext
接口中有两个泛型参数,因此需要为MakeGenericType
方法提供两个参数。
But , I'm not sure that it is what you need.但是,我不确定它是否是您所需要的。 You should map interfaces to some classes that might be initiated, not interfaces.
您应该将接口映射到一些可能启动的类,而不是接口。
services.AddScoped(typeof(IAppDBContext<,>), typeof(AppDBContext)); //example
But Do you really need to register open generic type?但是你真的需要注册开放泛型类型吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.