使用静态记录器、静态帮助器类进行依赖注入 [英] Dependency injection with a static logger, static helper class
问题描述
我有一个静态类,它调用一个静态 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
}
}
如何将 Logger 注入我的静态类?
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屋!