How to share an instance of a class with many clas

2019-06-24 15:06发布

I have a c# web service. When I get a new request I create a logging instance. I have many other instances of other classes to process the request and I want them to log as well. What is the best way to share logging instance without passing it in constructors or properties ?

7条回答
ゆ 、 Hurt°
2楼-- · 2019-06-24 15:32

You can use the Singleton Pattern to ensure that there is only a single instance of your logging object across the system.

Passing the logging object into the Constructor or as a property will actually make your code easier to test, depending on how you implement the Singleton pattern. Logging is one of those annoying cross-cutting concerns that always has trade-offs.

查看更多
欢心
3楼-- · 2019-06-24 15:35

Singleton Pattern.

That is, a class with a private constructor. You use a public static method to create only one instance of the class and return the object.

edit: also worth noting that you will need to put this class in its own project so that it can be referenced by all classes.

查看更多
冷血范
4楼-- · 2019-06-24 15:42

Well, you could make your logging class contain static methods which do the actual writing into memory/flushing to disk. You could also look into the Singleton Pattern

查看更多
虎瘦雄心在
5楼-- · 2019-06-24 15:42

Usually it's not a problem to create a new instance of your logger in each class. Log4Net logger constructor takes a type as a parameter to give you better logs.

查看更多
▲ chillily
6楼-- · 2019-06-24 15:46

Often some sort of static class / property is used to share an object without needing to pass references everywhere, for example:

public class Logger
{
    static Logger()
    {
        this.Instance - new Logger();
    }

    public static Logger Instance
    {
        get;
        private set;
    }

    // Other non-static members
}

Usage:

Logger.Instance.Log();

Often this (or at least variations on this) are referred to as the singleton pattern.

There are many variations on the above, for example the following slight variation is more common than the above in logging frameworks:

public class Logger
{
    static Logger()
    {
        this.Instance = new Logger();
    }

    public static Logger Instance
    {
        get;
        private set;
    }

    public static void Log() 
    {
        Logger.Instance.Log();
    }
}

Usage:

Logger.Log();
查看更多
贪生不怕死
7楼-- · 2019-06-24 15:53

Use a static field (I assume C# supports theses). The syntax should be similar to this:

private static final Logger logger = new Logger(...);

and just use that whenever you need to log something in the class.

查看更多
登录 后发表回答