【问题标题】:how to implement Open Generic Constructor Injection in Dot Net Core如何在 Dot Net Core 中实现 Open Generic Constructor Injection
【发布时间】:2020-10-16 18:22:28
【问题描述】:

我有一个审计日志接口:

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。 IAuditDbContext2[T1,T2]' for service type 'Common.Application.Interfaces.IAppDBContext2[T1,T2]'

请求帮助以正确实施。

【问题讨论】:

    标签: c# .net-core dependency-injection open-generics


    【解决方案1】:

    typeof(IAuditDbContext).MakeGenericType(typeof(AppDBContext))

    IAuditDbContext接口中有两个泛型参数,所以需要为MakeGenericType方法提供两个参数。

    但是,我不确定它是否是您所需要的。 您应该将接口映射到一些可能被启动的类,而不是接口。

    services.AddScoped(typeof(IAppDBContext<,>), typeof(AppDBContext)); //example
    

    但是你真的需要注册开放的泛型类型吗?

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      相关资源
      最近更新 更多