What information does a .NET class have about what is calling it?

.net, assemblies, class

Solution

You could get the information by looking at the stack trace:

StackTrace stackTrace = new StackTrace();            // Get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();   // Get method calls (frames)
string methodName = stackFrames[0].GetMethod().Name; // Get method name
string type = stackFrames[0].GetType().ToString();   // Get the calling type

However, I think the better solution would be to use a more object-oriented approach. Create different loggers that implement the same interface. Pass an instance of your logger to the class depending on what is creating and using the class.

public interface ILogger 
{
    void Log(string message);
}

public class MyWorkerClass
{
    private ILogger m_Logger;

    public MyWorkerClass(ILogger logger)
    {
        m_Logger = logger;
    }

    public void Work()
    {
        m_Logger.Log("working")
    }

    // add other members...
}

public class MyService
{
    public void DoSomething()
    {
        ILogger logger = new MyServiceLogger();
        MyWorkerClass worker = new MyWorkerClass(logger);
        worker.Work();
    }
}

Problem

I'm building a class project (seperate dll) that will contain various helper methods and common functionality, to be accessed by a range of different applications - an ASP.NET website, a web service and a Windows service. Is there any way that this neutral class can determine the type of application that is calling it (so it could, for example, make a choice about how to log information)? What other 'meta'-information is available to a class about what application is calling it?

Original source