I have a derived class of DbContext, called NavigationContext, that looks like this:
public class NavigationContext : DbContext
{
private readonly IConfiguration _configuration;
public NavigationContext(DbContextOptions<NavigationContext> options, IConfiguration configuration) : base(options)
{
_configuration = configuration;
}
//DbSets here ...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString("NavigationLoggingDatabase"));
}
}
}
The Configuration is registered to the DI container in Startup.cs, like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<NavigationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("NavigationLoggingDatabase")));
services.AddSingleton(_ => Configuration);
}
My question is what do I send to the NavigationContext constructor?
public int Add(TEntity item)
{
using (NavigationContext context = new NavigationContext(_contextOptionsBuilder.Options, ???))
{
context.Set<TEntity>().Add(item);
context.SaveChanges();
return item.Id;
}
}
new NavigationContext(...)at all, you're completely missing the point of DI if you do that.