Search code examples
c#reflectionsystem.reflection

How to get interface implementation type for currently executing method?


I have an interface with several implementations. The implementations and interface method call are in different packages if that matters. I'm trying to catch the exception that may occur during the method execution and log it with the implementation name after the method call. The implementation name is used in logs to differentiate in timeseries.a

try
{
    await _provider.Method();
    //_provider is declared as interface
}
catch (Exception e)
{
    //here I'm planning to log things including implementation that threw the error
    throw;
}

Is there a way to find interface implementation class that is executing the method in question without applying some regex to stack trace or modifying method in question for each implementation?

I tried using reflection and method info, but am only getting either all implementations or just interface information.


Solution

  • If you need to get the actual type of instance which is stored in the _provider just call GetType on it:

    try
    {
        await _provider.Method();
        //_provider is declared as interface
    }
    catch (Exception e)
    {
       var actualType = _provider.GetType();
       var typeFullName = actualType.FullName; // log the full name
       throw;
    }