Search code examples
c#constructorentity-framework-coreaspnetboilerplateprovider-model

System.ArgumentNullException when GetDbContext in constructor


I'm trying to use Entity Framework Core with ASP.NET Boilerplate .NET Core, but I don't want to use Repository built-in functions.

There is a problem with my DB context; it keeps returning:

System.ArgumentNullException: 'Value cannot be null.'

for the DbContext instance as shown below:

public class MainProjectsAppService : ApplicationService
{
    private readonly DecentralizationDbContext _ctx;

    public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
    {
        _ctx = dbContextProvider.GetDbContext();
    }

    public void CustomizedCreateMainProject(MainProject mainProject)
    {
        MainProject customizedMainProject = new MainProject
        {
            ...
        };

        _ctx.MainProjects.Add(customizedMainProject);
        _ctx.SaveChanges();
    }
}

My code screen shoot

Below is the DbContext class code:

namespace Decentralization.EntityFrameworkCore
{
    public class DecentralizationDbContext : AbpZeroDbContext<Tenant, Role, User, DecentralizationDbContext>
    {
        /* Define a DbSet for each entity of the application */

        public DbSet<MainProject> MainProjects { get; set; }
        public DecentralizationDbContext(DbContextOptions<DecentralizationDbContext> options)
            : base(options)
        {
        }
    }
}

Solution

  • Do not call dbContextProvider.GetDbContext() in the constructor.

    Define a getter instead:

    public class MainProjectsAppService : ApplicationService
    {
        private readonly IDbContextProvider<DecentralizationDbContext> _dbContextProvider;
        private DecentralizationDbContext _ctx => _dbContextProvider.GetDbContext();
    
        public MainProjectsAppService(IDbContextProvider<DecentralizationDbContext> dbContextProvider)
        {
            _dbContextProvider = dbContextProvider;
        }
    }
    

    Reference: aspnetboilerplate/aspnetboilerplate#4809