I'm building ASP.Net app which is a simulator, lots of action will happens outside of Controller as separate threat, but I'm struggling to create DbContext connection outside of Controller. I know I could use OnConfiguring(DbContextOptionsBuilder optionsBuilder) but it doesn't look to my as most elegant way to do it.
I through something like this should work:
public class SimRepository : ISimRepository
{
public IConfiguration _configuration;
public DbContextOptionsBuilder _dbOptions;
public SimRepository(IConfiguration configuration)
{
_configuration = configuration;
_dbOptions = new DbContextOptionsBuilder();
_dbOptions.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
}
public void LatheIn()
{
using (AppDbContext db = new AppDbContext(_dbOptions.Options))
{
}
}
}
but I receive this error:
Argument 1: cannot convert from Microsoft.EntityFrameworkCore.DbContextOptions' to Microsoft.EntityFrameworkCore.DbContextOptions<Simulator_Line.Server.AppDbContext>
In Startup:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
//Enable use of appsettings.json outside of Startup.cs
services.AddSingleton(Configuration);
services.AddSingleton<IConfiguration>(Configuration);
}
If my approach is incorrect, I'm open to for changes.
EDIT
public class LatheController : Controller
{
private readonly AppDbContext _dbContext;
private readonly SimRepository _simRrepo;
public LatheController(AppDbContext dbContext, SimRepository latheRepo)
{
_dbContext = dbContext;
_simRrepo = latheRepo;
}
[HttpGet]
public IEnumerable<Lathe> GetLathes()
{
_simRrepo.LatheIn();
return _dbContext.Lathes;
}
}