Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with DbContext - creating instance in Startup.cs

I am using ASP.net core. I have problem with implementing dbcontext into singleton.

I need my singleton IModuleRepository to be running right after start of the project. So I am creating new instance of this dependency in public void ConfigureServices(IServiceCollection services) in Startup.cs file.

This singleton is using another singleton, so I am using it like this:

services.AddDbContext<ModulesDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging());
...    
services.AddSingleton<IModuleRepository, ModuleRepository>();
services.AddSingleton<ICommunicationRepository>(new CommunicationRepository(services.BuildServiceProvider().GetService<IModuleRepository>()));

In ModuleRepository I am using DBcontext.

// Db context
    private readonly ModulesDbContext _modulesDbContext;

    public ModuleRepository(ModulesDbContext modulesDbContext)
    {
        _modulesDbContext = modulesDbContext;
    }

When I am calling _modulesDbContext.SomeModel.ToList(); I get error:

System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point.

How to avoid this error when I need this singleton to run after the project is started?

Thank you for your help.

like image 527
David Pavelka Avatar asked Mar 02 '26 15:03

David Pavelka


1 Answers

As @Ilya Chumakov commented, you could just tell the DI container to use your concrete class like so:

services.AddSingleton<ICommunicationRepository, CommunicationRepository>();

Then any class can depend on ICommunicationRepository and get the concrete repository, which gets the Db context.

like image 190
juunas Avatar answered Mar 05 '26 05:03

juunas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!