Jun 14, 2022
Per Djurner

Using DbContext in a .NET singleton service

It is perhaps not considered best practice, but it can be done. Here's some example code for when you have registered MyService as a singleton and want to access MyDbContext from inside it.

using MyProject.Data;
using Microsoft.Extensions.DependencyInjection;

namespace MyProject.Services
{
    public class MyService
    {
        private readonly IServiceScopeFactory _scopeFactory;

        public MyService(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;
        }

        public void MyMethod()
        {
            using var scope = _scopeFactory.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<MyDbCtx>();
        }
    }
}

Home