Davide Quaglio
Davide Quaglio

Reputation: 771

EF Core reusable DbContext

I'm trying to create a reusable base for future web applications made with asp net core. I created a library that contains a BaseDbContext that inherit from IdentityDbContext:

public class BaseDbContext : IdentityDbContext<ApplicationUser>
    {
        public BaseDbContext(DbContextOptions options) : base(options)
        {

        }   
    }

Inside this library there are some services for login and creation of Users.

Everytime that I will be creating a new WebApplication I will reference the library and I will create a new DbContext like this:

public class ProjectDbContext : BaseDbContext
{
    //some generics DBSET
    public ProjectDbContext (DbContextOptions<ProjectDbContext> options) : base(options)
    {
    }
}

And in the startup:

    services.AddDbContext<ProjectDbContext>(options =>
    {
        options.UseSqlServer(connection);
    });

Since the service for the login and creation of users require a reference of BaseDbContext, I created a IDbContextFactory inside the base project that will be implemented by the main project like this:

public class ProjectContextFactory : IDbContextFactory
{
    private readonly ProjectDbContext _projectDbContext;

    public ProjectDbContextFactory(ProjectDbContext remDbContext)
    {
        _remDbContext = remDbContext;
    }

    public BaseDbContext GetBaseDbContext()
    {
        return _projectDbContext;
    }
}

This factory will be used inside the base project to get a reference to the BaseDbContext.

Is this a good thing to do? Can this create some kind of problems?

Upvotes: 0

Views: 1213

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239220

In general, no, this is not a good thing to do.

that will contains the entities that will be used for all web applications

If there's entities that are common to all projects, then those should be factored out completely. In other words, you'd have one project (your base project) with a context like UserContext, which will have your User and Credential entities, and then every other project would have its own separate context that deals with just what it needs. If the other application(s) need to access users, they'd either do so via an instance of UserContext or, better, through a service, such as an API.

That said, it sounds like you're rolling your own auth, which you should emphatically not do. Use Identity. And, if you need to share that between applications, you need a centralized auth provider, such as Identity Server.

Upvotes: 1

Related Questions