Is it possible to use Audit.Core with Worker Service project type ? #651
Replies: 2 comments 9 replies
-
I believe that incorporating Audit.NET seamlessly with a Worker Service will not provide too much value, as the library might not have extensive points of integration to facilitate a standardized approach for auditing. But you could use the AuditScope in your background service, for example: using Audit.Core;
public class Worker : BackgroundService
{
private AuditScope? _auditScope;
public override Task StartAsync(CancellationToken cancellationToken)
{
_auditScope = AuditScope.Create(new AuditScopeOptions()
{
CreationPolicy = EventCreationPolicy.InsertOnEnd
});
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_auditScope!.SetCustomField("WorkerExecutionStart", DateTimeOffset.Now);
int i = 0;
while (!stoppingToken.IsCancellationRequested)
{
_auditScope.Comment($"Worker {++i} running at: {DateTimeOffset.Now}");
try
{
await DoSomeWorkAsync(stoppingToken);
}
catch (Exception e)
{
_auditScope.SetCustomField("Exception", e.Message);
throw;
}
}
_auditScope!.SetCustomField("WorkerExecutionEnd", DateTimeOffset.Now);
}
private async Task DoSomeWorkAsync(CancellationToken ct)
{
// do some work...
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
await _auditScope!.DisposeAsync();
}
public override void Dispose()
{
_auditScope?.Dispose();
base.Dispose();
}
} |
Beta Was this translation helpful? Give feedback.
-
@thepirat000 - This actually would be extremely valuable for integrating Audit.Net into RabbitMQ/MassTransit which is actually something I'm struggling with myself. Such systems use a BackgroundService as a means to forward messages to RabbitMQ, therefore a DataProvider would have to somehow forward messages into the BackgroundService. Would love to see this native in Audit.Net. |
Beta Was this translation helpful? Give feedback.
-
Hello everyone.
I'd like to know if it's possible to use Audit.NET with Worker Service Project or Console Application/Windows Application
For example, by using data annotation as the same way we use it on Web API.
E.G
Web API
[AuditApi(EventTypeName = "My custom event")]
public async Task Post([FromBody] model)
Worker Service
[Audit (?????)
public override Task StartAsync(CancellationToken cancellationToken)
Thank you all
Beta Was this translation helpful? Give feedback.
All reactions