繁体   English   中英

如何在 Dot Net Core 中实现 Open Generic Constructor Injection

[英]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)));

我也尝试过其他方法,但无法成功 - 我收到的一些错误消息是:

错误信息:

  1. Message=提供的泛型参数的数量不等于泛型类型定义的数量。
  2. 无法实例化实现类型“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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM