EF Core reusable DbContext

asp.net-core c# entity-framework-core

Question

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?

1
0
9/11/2019 6:28:18 PM

Accepted Answer

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.

1
9/9/2019 1:43:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow