I have one c# project which is using libraries from Ardalis Specification , I need to work with two different DbContext.
So, from Autofac side I need to register generics which will implement IRepository, IReadRepository .With my current code when I should use repository related to one SapScriptDbContext it is throwing me an error “System.ArgumentException: Cannot create a DbSet for ‘CooisHeader’ because this type is not included in the model for the context.”
public class AppEfRepository<T> : RepositoryBase<T>,IReadRepository<T>,IRepository<T> where T : class,IAggregateRoot
{
public AppEfRepository(ApplicationDbContext context):base(context)
{
}
}
public class SapScriptDbContext : DbContext
{
public SapScriptDbContext(DbContextOptions<SapScriptDbContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CooisHeader>().ToTable("CooisHeader");
modelBuilder.Entity<CooisComponent>().ToTable(nameof(CooisComponent));
}
public DbSet<CooisHeader> CooisHeader => Set<CooisHeader>();
public DbSet<CooisComponent> CooisComponent => Set<CooisComponent>();
}
public class AutofacInfrastructureModule : Module
{
private readonly List<Assembly> _assemblies = new List<Assembly>();
public AutofacInfrastructureModule(Assembly? callingAssembly = null)
{
AddToAssembliesifNotNull(callingAssembly);
}
private void AddToAssembliesifNotNull(Assembly callingAssembly)
{
if (callingAssembly != null)
{
_assemblies.Add(callingAssembly);
}
}
protected override void Load(ContainerBuilder builder)
{
LoadAssemblies();
RegisterEf(builder);
}
private void LoadAssemblies()
{
var coreAssembly = Assembly.GetAssembly(typeof(CooisHeader));
var appCore = Assembly.GetAssembly((typeof(Cut)));
var infrastructureAssembly = Assembly.GetAssembly(typeof(AutofacInfrastructureModule));
AddToAssembliesifNotNull(coreAssembly);
AddToAssembliesifNotNull(appCore);
AddToAssembliesifNotNull(infrastructureAssembly);
}
private void RegisterEf(ContainerBuilder builder)
{
builder.RegisterGeneric(typeof(SapScriptEfRepository<>))
.As(typeof(IRepository<>))
.As(typeof(IReadRepository<>))
.InstancePerLifetimeScope();
//If I comment this bellow app is working and no error
builder.RegisterGeneric(typeof(AppEfRepository<>))
.As(typeof(IRepository<>))
.As(typeof(IReadRepository<>))
.InstancePerLifetimeScope();
}
}
From Program.cs
var connectionString = builder.Configuration.GetConnectionString("SapScriptConnection");
var defaultConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SapScriptDbContext>(cfg => cfg.UseSqlServer(connectionString));
builder.Services.AddDbContext<ApplicationDbContext>(cfg => cfg.UseSqlServer(defaultConnectionString));
I’m trying to resolve DI with autofac where I can use generic repository for multiple dbcontexts