Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DbContext in another class asp.net core 2

In my Controller I have this

private readonly DbContext _context;

public CountryController(DbContext context)
{
    _context = context;
}

How can I retrieve DbContext in other classes like static classes without passing as parameter to the method call

like image 882
Navigator Avatar asked Nov 07 '22 12:11

Navigator


1 Answers

You can create new instances of your DBContext by creating services. First you have to define an interface

public interface IMyService
{
    void Test1();
}

then, you need to create the service class implementing the interface. Note that you request IServiceProvider to the Dependency Injector.

internal sealed class MyService : IMyService
{
    private readonly IServiceProvider m_ServiceProvider;
    // note here you ask to the injector for IServiceProvider
    public MyService(IServiceProvider serviceProvider)
    {
        if (serviceProvider == null)
            throw new ArgumentNullException(nameof(serviceProvider));
        m_ServiceProvider = serviceProvider;
    }

    public void Test1()
    {
        using (var serviceScope = m_ServiceProvider.CreateScope())
        {
            using (var context = serviceScope.ServiceProvider.GetService<DbContext>())
            {
                // you can access your DBContext instance
            }
        }
    }
}

finally, you instruct the runtime to create your new service a singleton. This is done in your ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // other initialization code omitted
    services.AddMvc();

    services.AddSingleton<IMyService, MyService>();

    // other initialization code omitted
}

Note that MyService needs to be thread safe.

like image 73
Yennefer Avatar answered Dec 06 '22 19:12

Yennefer