I want Register my DbContext service and after registration is successful, want pass to that created instance (dbcontext.SavingChanges) an event handler (AuditingSupport.) . My problem is service which hold that event handler (AuditingSupport.UpdateAuditableEntity) is using DbContext through DI. Try to solve that with autofac OnActivated() method, but throwing exception Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'DIT.Persistence.EF.Repositories.Domain.AppUserService'.' when on runtime try to get DbContext Service.
Example of configuration and registration.
AuditingSupport.cs implementation :
public class AuditingSupport : IAuditingSupport
{
public AuditingSupport(IAppUserService userService)
{
this.userService = userService;
}
// EventHandler method which want pass to dbContext.SavingChanges event
public void UpdateAuditableEntity(object sender, SavingChangesEventArgs e)
{
...
}
}
AppUserService.cs implementation:
public class AppUserService : IAppUserService
{
// Consume DbContex through DI
public AppUserService(DbContext context)
{
...
}
...
}
Registre class for DcContext DcContextModule.cs :
public class DcContextModule : Module
{
...
public DcContextModule (IConfiguration configuration, IServiceCollection services)
{
this.configuration = configuration;
this.services = services;
}
protected override void Load(ContainerBuilder builder)
{
// In this OnActivated() autofac method I try to get Auditing Service and pass event hanlder method
builder.RegisterType<EUDbContext>()
.As<DbContext>()
.WithParameter("options", this.GetOptions())
.InstancePerLifetimeScope()
.OnActivated(x => x.Instance.SavingChanges += services.BuildServiceProvider().GetRequiredService<IAuditingSupport>().UpdateAuditableEntity);
}
}
Program.cs service Registration:
//Register Service
...
builder.Services.AddTransient<IAuditingSupport, AuditingSupport>();
builder.Services.AddSingleton<IAppUserService, AppUserService>();
builder.Host.ConfigureContainer<ContainerBuilder>(builder0 => builder0.RegisterModule(new DbContextModule(configuration, builder.Services)));
...
// Call Service
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
// Exception throw
var audit = services.GetRequiredService<IAuditingSupport>();
var context = services.GetRequiredService<DbContext>();
}
}
I Would like to know how to solve this problem and is this good approach. Can I solve it without autofac and how ?