Created
August 18, 2016 15:46
-
-
Save phil-scott-78/0f71253afa75040cae47cf9c5ac40199 to your computer and use it in GitHub Desktop.
Command interceptor to include caller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Performance seems ok.
To add call this once per application