依赖注入与静态记录器,静态助手类 [英] Dependency injection with a static logger, static helper class

查看:136
本文介绍了依赖注入与静态记录器,静态助手类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态类调用静态Logger类,

I have a static class which calls a static Logger class,

例如

static class DoesStuffStatic
{
  public static void DoStuff()
  {
    try
    {
      //something
    }
    catch(Exception e)
    {
      //do stuff; 
      Logger.Log(e);
    }
  }
}

static class Logger
{
  public static void Log(Exception e)
  {
     //do stuff here
  }
}

如何注入记录器进入我的静态类?

How do I inject the Logger into my static class?

注意:我已经阅读了 .NET中的依赖注入示例?,但这似乎使用一个实例记录器。

Note: I've read Dependency Injection in .NET with examples?, but this seems to use an instance logger.

推荐答案

不能注入静态记录器。您必须将其更改为实例记录器(如果可以),或将其包装在实例记录器中(将调用静态)。此外,将静态类注入到任何东西(因为您不以任何方式控制静态构造函数)是非常困难的 - 这就是为什么我倾向于将所有要注入的对象传递给参数。

You can't inject a static logger. You have to either change it to an instance logger (if you can), or wrap it in an instance logger (that will call the static). Also it is fairly hard to inject anything to a static class (because you don't control the static constructor in any way) - that's why I tend to pass all the objects I want to inject as parameters.

这篇关于依赖注入与静态记录器,静态助手类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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