how to implement Open Generic Constructor Injection in Dot Net Core

1.3k views Asked by At

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:

public interface IAppDBContext<T1, T2> : IAuditDbContext<T1,T2>
{
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}

and in main AppDbContext class, I am inheriting as:

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:

  1. Message=The number of generic arguments provided doesn't equal the arity of the generic type definition.
  2. Cannot instantiate implementation type 'Common.Application.Interfaces. IAuditDbContext2[T1,T2]' for service type 'Common.Application.Interfaces.IAppDBContext2[T1,T2]'

Requesting help to implement it correctly.

1

There are 1 answers

0
Egor Popov On

typeof(IAuditDbContext<,>).MakeGenericType(typeof(AppDBContext))

You have two generic parameters in IAuditDbContext interface, so you need to provide two parameters for MakeGenericType method.

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?