efcore icon indicating copy to clipboard operation
efcore copied to clipboard

ModelBuilder Needs to support DI.

Open afoliaco opened this issue 11 years ago • 7 comments

During the creation of dbContext ModelBuilder needs to support injection as a singleton.

afoliaco avatar Jul 30 '15 20:07 afoliaco

not sure how to change this from issue to enhancement see StackOverFlow question http://stackoverflow.com/questions/29761348/ef7-injecting-model-configuration

afoliaco avatar Jul 30 '15 20:07 afoliaco

@SonOfSam I think rather than putting the ModelBuilder in DI you want to construct your model and set it on the DbContextOptions that are registered in DI.

var builder = new ModelBuilder();
// all the code to configure your model
var model = builder.Model;

services.AddEntityFramework()
    .AddSqlServer()
    .AddDbContext<MyDbContext>(options =>
    {
        options.UseSqlServer("<connection string>");
        options.UseModel(model);
    });

rowanmiller avatar Jul 30 '15 20:07 rowanmiller

Hi Ron, Thanks for the reply, by the way huge fan. The problem with that approach is that the application must use a dbcontext in the startup.cs, the goal of the application is to be db agnostic. I have 2 factories one that generate configuration depending on the tenant database selection and another factory that generate a repository that does all the data manipulation. I was able to do this configuration injection for MongoDB using their C# driver but I can't do this with EF because modelbuiler is part of dbcontext.

see question here http://stackoverflow.com/questions/29113206/change-injected-object-at-runtime

afoliaco avatar Jul 30 '15 20:07 afoliaco

@SonOfSam can you just register a factory in DI that is responsible for creating a context based on which database you want to connect to? You can create a DbContextOptions instance (with the connection string and model) externally and pass it into the context, so you can use the same context type with a different connection and different mapping etc. for each database. Components would then get the factory from DI and tell it which database they want to get a repository for.

rowanmiller avatar Aug 05 '15 18:08 rowanmiller

Hi @rowanmiller I'm going to create a sample DB Agnostic using a blog models, once I'm I'm to try to apply your suggestion. Thanks your help.

afoliaco avatar Aug 06 '15 12:08 afoliaco

@SonOfSam Sounds good. I'm going to close this issue out but feel free to reopen it if you have further questions/issues once you try it out.

rowanmiller avatar Aug 06 '15 16:08 rowanmiller

@rowanmiller U make my day ! Thanks @rowanmiller !

Diaskhan avatar Apr 20 '19 09:04 Diaskhan