我正在构建一个应用程序,使用 AutoFac 2 进行依赖注入。 我已经阅读过资料,了解到应该避免使用静态 IoCHelper (服务定位器)。
IoCHelper.cs
public static class IoCHelper
{
private static AutofacDependencyResolver _resolver;
public static void InitializeWith(AutofacDependencyResolver resolver)
{
_resolver = resolver;
}
public static T Resolve<T>()
{
return _resolver.Resolve<T>();
}
}
从之前的问题的答案中,我找到了一种通过使用自动生成工厂来帮助减少在我的UnitOfWork中使用IoCHelper的方法。继续沿着这条路走,我想知道是否可以完全消除我的IoCHelper。
以下是场景:
我有一个静态的Settings类,它作为我的配置实现的包装器。由于Settings类是大多数其他类的依赖项,该包装器使我不必在整个应用程序中注入设置类。
Settings.cs
public static class Settings
{
public static IAppSettings AppSettings
{
get
{
return IoCHelper.Resolve<IAppSettings>();
}
}
}
public interface IAppSettings
{
string Setting1 { get; }
string Setting2 { get; }
}
public class AppSettings : IAppSettings
{
public string Setting1
{
get
{
return GetSettings().AppSettings["setting1"];
}
}
public string Setting2
{
get
{
return GetSettings().AppSettings["setting2"];
}
}
protected static IConfigurationSettings GetSettings()
{
return IoCHelper.Resolve<IConfigurationSettings>();
}
}
有没有一种方法可以在不使用服务定位器的情况下处理这个问题,而且不必将AppSettings注入到每个类中?以下是我在三个方面上依赖ServiceLocator而不是构造函数注入的原因:
- AppSettings
- 日志记录
- 缓存