What information does the .NET class have about what is called?

I am creating a class project (a separate dll) that will contain various helper methods and general functionality that can be accessed using various applications - the ASP.NET website, web services and Windows services.

Is there a way that this neutral class can determine the type of application that calls it (so that it can, for example, make a choice how to record information)?

What other "meta information" is available to the class about which application calls it?

+3
source share
5 answers

You can get 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

, - . , . , .

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();
    }
}
+5

, . , .

, , , .

, , . , , LogMessage, LogError ..,

+9

, NLog Log4Net, . , , (, , ..).

0

, , , , , .

, , , , , , - . (IMHO, , , , , .Net)

0

. - .

Change these "If his a X makes it Y, if his choice A makes it B", using dependency injection . Those behaviors that change in different contexts must be encapsulated in objects that implement a common interface. The caller will determine which interface implementation he wants to use and inject into his instance before calling his methods.

0
source

Source: https://habr.com/ru/post/1716782/


All Articles