5

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.