如何与多个类共享一个类的实例? [英] How to share an instance of a class with many classes?

查看:226
本文介绍了如何与多个类共享一个类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#Web服务.收到新请求时,我将创建一个日志记录实例.我还有许多其他类的其他实例来处理请求,我也希望它们也记录下来.共享日志实例而不在构造函数或属性中传递日志的最佳方法是什么?

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 ?

推荐答案

Singleton模式是反模式;我想不出应该在其中使用或推荐使用日志的许多情况,包括本例中的日志记录.

Singleton Pattern is an anti-pattern; I can not think of many instances where it should be used or recommended, including in this instance, for logging.

我们如何处理日志记录:日志记录实例通过构造函数注入被注入到需要它的所有类中.例如:

How we handle logging: A logging instance is injected into all classes that need it via constructor injection. For example:

public class MyClass
{
    private readonly ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }

    public void DoStuff()
    {
        _logger.Trace("DoStuff called");
    }
}

注入的日志记录实例可以每次都是一个新实例,或者如果您打算使用单个实例记录器,则可以创建一次并根据需要进行传递.

The logging instance injected can either be a new instance each time, or if you are bent on having a single instance logger it can be created once and passed through as needed.

但是:我强烈建议第一种选择,使用DI使用

However: I strongly recommend the first option, using DI to construct your classes using the Composition Root pattern. I also recommend using a logging framework, such as NLog or log4net. These are configurable and easy to use with emails, event viewer, files, etc. and work in multi threaded environments.

我们有自己的ILogger定义,其中包含Trace,Warn,Info,Exception等,然后使用NLog实现此接口.这意味着我们可以通过创建ILogger的新实现,然后进行简单的DI配置更新来轻松更改日志记录方式.到目前为止,这是一个非常有效的日志记录解决方案.

We have our own definition of ILogger which has Trace, Warn, Info, Exception, etc., and then implemented this interface using NLog. This means that we can easily change how we log by creating a new implementation of ILogger and then making a simple DI config update. This is one logging solution that has worked really well for us so far.

这篇关于如何与多个类共享一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆