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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With