我有一个调用静态 Logger 类的静态类,
例如
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 注入(inject)我的静态类?
注意:我读过Dependency Injection in .NET with examples? ,但这似乎使用了一个实例记录器。
最佳答案
不一定如此。只要您的静态记录器公开以下方法:
- 注入(inject)你想要注入(inject)的类,或者
- 在运行 DI 容器之前在适当的方法调用中注入(inject)它(比如在 asp.net global.asax Application_Start 方法中),那么你应该没问题。
这是一个例子。参加以下 DI 类(class):
public class Logger : ILogger
{
public void Log(string stringToLog)
{
Console.WriteLine(stringToLog);
}
}
public interface ILogger
{
void Log(string stringToLog);
}
这是我们的静态类,它需要一个记录器:
public static class SomeStaticClass
{
private static IKernel _diContainer;
private static ILogger _logger;
public static void Init(IKernel dIcontainer)
{
_diContainer = dIcontainer;
_logger = _diContainer.Get<ILogger>();
}
public static void Log(string stringToLog)
{
_logger.Log(stringToLog);
}
}
现在,在您的应用程序的全局启动中(在本例中,在我的 global.asax.cs 中),您可以实例化您的 DI 容器,然后将其交给您的静态类。
public class Global : Ninject.Web.NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
return Container;
}
static IKernel Container
{
get
{
var standardKernel = new StandardKernel();
standardKernel.Bind<ILogger>().To<Logger>();
return standardKernel;
}
}
void Application_Start(object sender, EventArgs e)
{
SomeStaticClass.Init(Container);
SomeStaticClass.Log("Dependency Injection with Statics is totally possible");
}
很快!您现在已在静态类中启动并运行 DI。
希望对某人有所帮助。我正在重新开发一个使用大量静态类的应用程序,我们已经成功使用它一段时间了。
关于c# - 使用静态记录器、静态帮助程序类进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1293489/