Skip to content

Instantly share code, notes, and snippets.

@phil-scott-78
Created August 18, 2016 15:46
Show Gist options
  • Save phil-scott-78/0f71253afa75040cae47cf9c5ac40199 to your computer and use it in GitHub Desktop.
Save phil-scott-78/0f71253afa75040cae47cf9c5ac40199 to your computer and use it in GitHub Desktop.
Command interceptor to include caller
public class CallerCommandInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) => AddCaller(command);
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) => AddCaller(command);
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) => AddCaller(command);
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { }
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { }
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) { }
private static void AddCaller(DbCommand command)
{
var stack = new StackTrace(false);
var frames = stack.GetFrames();
if (frames == null) return;
var sb = new StringBuilder();
foreach (var frame in frames)
{
var method = frame.GetMethod();
if (method.Module.Name.StartsWith("CompanyName", StringComparison.CurrentCultureIgnoreCase) == false || method.ReflectedType?.Name == "CallerCommandInterceptor")
continue;
sb.AppendLine($" -- Caller: {method.ReflectedType?.Name}.{method.Name}");
}
command.CommandText = sb.ToString() + command.CommandText;
}
}
@phil-scott-78
Copy link
Author

Performance seems ok.
image

To add call this once per application

DbInterception.Add(new CallerCommandInterceptor());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment