依赖注入与静态记录器,静态助手类

问题描述:

我有一个静态类调用静态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.