Reputation: 3133
We have an ASP.NET Core 5.0 and EF Core 5.0 project. We'd like to implement a query counter which will look at how many EF Core queries executed against a database during an API execution. The DbContext
is injected to the controllers using ASP.NET DI with AddScoped
method.
Anyone have any ideas of how to implement this? Maybe with a EF Core interceptor or something?
Upvotes: 0
Views: 848
Reputation: 21
You can use Event Counters
I think this tool will solve the problem.
Upvotes: 1
Reputation: 27336
Easiest way to do that is using IDbCommandInterceptor
Create class which is derived from DbCommandInterceptor
. It should be thread safe.
public class MyCommandInterceptor : DbCommandInterceptor
{
public IMyStatistics Statistics { get; }
public MyCommandInterceptor(IMyStatistics statistics)
{
Statistics = statistics ?? throw new ArgumentNullException(nameof(statistics));
}
public override DbCommand CommandCreated(CommandEndEventData eventData, DbCommand result)
{
Statistics.IncrementCommandCount();
return base.CommandCreated(eventData, result);
}
}
Collect data using IMyStatistics
interface. Realization also should be thread safe.
public interface IMyStatistics
{
long CommandCount { get; }
long IncrementCommandCount();
}
public class MyStatistics : IMyStatistics
{
private long _commandCount;
public long CommandCount => _commandCount;
public long IncrementCommandCount()
{
return Interlocked.Increment(ref _commandCount);
}
}
And configure your options:
_statistics = new MyStatistics();
optionsBuilder.AddInterceptors(new MyCommandInterceptor(_statistics));
Ensure that _statistics
is singleton or created in right scope.
Upvotes: 1