I have .NET Core 2.1 WebAPI project. I create base DbContext which name is DataContext.cs
. I want to start DataContext
by IAuditHelper
. When project start, I can set AuditHelper
from my Startup.cs.
But, after project start and execute SaveChangesAsync
method, it's being null. How, can I achieve getting AuditHelper from My DataContext? (I know, if I inject IAuditHelper in my DataContext constructor, then I can take. But, in that situation, Datacontext wants IAuditHelper in everywhere.)
DataContext.cs
public class DataContext : DbContext,IDataContext
{
public IAuditHelper AuditHelper { get; set; }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
auditHelper.LogMyChangesToDatabase()
return (await base.SaveChangesAsync(true, cancellationToken));
}
}
IDataContext.cs
public interface IDataContext : IDisposable
{
IAuditHelper AuditHelper{ get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
Task<int> SaveChangesWithoutAuditAsync(CancellationToken cancellationToken);
}
UniversityDbContext.cs
public class UniversityDbContext: DataContext
{
override protected void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.; database=.; user id=.;
password=.;");
}
public UniversityDbContext() : base()
{
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IAuditHelper, AuditHelper>();
services.AddScoped<IDataContext, DataContext>();
services.AddScoped<DataContext, UniversityDbContext>();
services.AddDbContext<UniversityDbContext>();
var sp = services.BuildServiceProvider();
var dataContext = sp.GetService<IDataContext>();
dataContext.AuditHelper = sp.GetService<IAuditHelper>();
}