I have a custom class LoggingDbConnection that implements IDbConnection. This LoggingDbConnection class has its own public instance method, for example, QueryAsync<T>(...), which includes custom logging logic.
In my service, I have a field:
private readonly IDbConnection _dbConnection;
This field is injected (e.g., via Autofac) with an instance of LoggingDbConnection.
When I call:
await _dbConnection.QueryAsync<T>(...);
I expect my LoggingDbConnection.QueryAsync<T>() instance method (with the logging) to be executed because the actual runtime object is a LoggingDbConnection.
However, what actually happens is that Dapper's QueryAsync<T>() extension method (for IDbConnection) gets called instead, and my custom logging is bypassed.
Why does the C# compiler choose Dapper's extension method for IDbConnection instead of the instance method on my concrete LoggingDbConnection class, even though the object instance at runtime is a LoggingDbConnection?
IDbConnection, you can only call methods of this interface or extension methods. The compiler doesn't know that anIDbConnectionis actually aLoggingDbConnectionwith different functions.