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

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

问题描述

我有调用静态的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?

请注意:我读过<一个href=\"http://stackoverflow.com/questions/743951/help-with-dependency-injection-in-net\">http://stackoverflow.com/questions/743951/help-with-dependency-injection-in-net,但这似乎使用实例记录。

Note: I've read http://stackoverflow.com/questions/743951/help-with-dependency-injection-in-net, 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天全站免登陆