Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 multiple dbcontext problems

I'm playing around with the new ASP.NET 5 beta 8 and having trouble when I have two dbcontext.

I have the following project structure.

-Data(Identity 3 db with other entities)
-Resources (Contains a db with translations)
-WebApp 

Stripped away some code in Startup.cs in WebApp

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<DatabaseContext>(opt => opt.UseSqlServer(Configuration["Data:MainDb:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<DatabaseContext>()
            .AddDefaultTokenProviders();

        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ResourceDbContext>(opt => opt.UseSqlServer(Configuration["Data:Resources:ConnectionString"]));

        services.AddTransient<IResourceDbContext, ResourceDbContext>();
        services.AddTransient<IDatabaseContext, DatabaseContext>();
}

In both ResourceDbContext and DatabaseContext I do the following

    public ResourceDbContext(DbContextOptions options) : base(options)
    {
        _connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
    }


    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(_connectionString);
    }

However when I read my connectionstrings from appsettings.json I receive the correct values in ConfigureServices. But the DbContextOptions only contains the latest loaded value, in this case the connectionstring for Resources. So both dbcontext establishes a connection to Resource db.

I'm unable to find any information about this.

like image 292
user1619493 Avatar asked May 28 '26 08:05

user1619493


1 Answers

All you need to do is indicate that DbContextOptions is a generic type:

public ResourceDbContext(DbContextOptions<ResourceDbContext> options) : base(options)
{

}

Now the dependency injection system can find the right dependency (DbContextOptions options) at the moment it creates ResourceDbContext and injects it into the constructor.

See implementation AddDbContext method


For Miroslav Siska:

public class GetHabitsIdentity: IdentityDbContext<GetHabitsUser, IdentityRole, string> where TUser : IdentityUser
{
    public GetHabitsIdentity(DbContextOptions<GetHabitsIdentity> options)
        :base(options)
    {

    }        
}
like image 186
Stas Boyarincev Avatar answered May 31 '26 04:05

Stas Boyarincev