Audit.NET icon indicating copy to clipboard operation
Audit.NET copied to clipboard

Audit.Net doesn't work with default asp.net Core DI

Open sanshep1332 opened this issue 3 years ago • 2 comments

Good afternoon. I tried to use this library in my Asp.Net Core application. I need to collect logs from my Web.Api app (via audit.net.webapi), and from the server (audit.net). To do this, I created a custom provider, in which, through DI asp.net.core I inject the implementation of a Repository that can work with the database via EF:

private readonly IMapper _mapper;
private readonly AuditLogRepository _repository;

publicAuditLogDataProvider(
    imapper mapper,
    AuditLogRepository repository)
{
    _mapper = mapper;
    _repository = repository;
}

In the InsertEventAsync method, I make the code I need and call the repository methods to add the log to the database.

The repository uses the Ef DB Context, which is also injected through DI:

private readonly AuditLogDbContext _dbContext;

public AuditLogRepository(AuditLogDbContext context)
{
     _dbContext = context;
}

When calling any method, the DB Context will fail with the error "Cannot access a disposed context instance error".

After a short digging in the repository, I found this line in AuditApiAdapter.Core.AfterExecutedAsync:

await auditScope.DisposeAsync();

I think this is the reason for calling Dispose on the DB Context before it had time to be called.

Is there any plan to support DI in the future? Or is there some other way to avoid this error?

Audit.net setup:

Program.cs:

Audit.Core.Configuration.Setup()
 .UseCustomProvider(services.GetRequiredService<AuditDataProvider>())
 .WithCreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd);

Startup.cs

services.AddScoped<AuditDataProvider, AuditLogDataProvider>();
services.AddMvc(mvc =>
{
    mvc.AddAuditFilter(config =>
    config.LogAllActions()
        .IncludeHeaders()
        .IncludeModelState()
        .IncludeRequestBody()
        .IncludeResponseBody()
        .IncludeResponseHeaders());
});

sanshep1332 avatar Aug 08 '22 12:08 sanshep1332

Please check if https://github.com/thepirat000/Audit.NET/issues/194 or https://github.com/thepirat000/Audit.NET/issues/387 helps

thepirat000 avatar Aug 09 '22 05:08 thepirat000

Try with .UseFactory instead:

Audit.Core.Configuration.Setup()
    .UseFactory(() => services.GetRequiredService<AuditDataProvider>())

The call to auditScope.DisposeAsync() will not dispose the DbContext

thepirat000 avatar Aug 10 '22 02:08 thepirat000

Closing this for inactivity, if it's still an issue please comment

thepirat000 avatar Aug 26 '22 05:08 thepirat000