ServiceLocator通过传递构造参数

时间:2015-06-09 01:36:46

标签: c# asp.net unity-container service-locator

如何使用下面的构造函数获取带有服务定位器的对象实例。 ProductCode是用于初始化成员属性的构造函数参数。对于所有其他构造函数参数,我已在global.asax文件中使用unity注册它们。

如果构造函数参数是引用类型,则获取对象实例的基本方法:

var productSettingsRepo = 
      ServiceLocator.Current.GetInstance<ProductSettingsRepository>();

public ProductSettingsRepository(ILogWriter logWriter, 
          ISecurityFunctionRepository securityRepo,
          IProductSettingsManager productSettingsManager,
          IReferenceDataService referenceDataService, 
          string productCode)
      {
          _logWriter = logWriter;
          _securityRepo = securityRepo;
          _productSettingsManager = productSettingsManager;
          _referenceDataService = referenceDataService;
          ProductInfo = GetProductData(productCode);
      }

1 个答案:

答案 0 :(得分:3)

服务定位器模式is considered an anti-pattern,您可能希望重构使用Dependency Injection

话虽如此,这里有一种方法可以解决您的问题,而无需重构:

创建一个依赖于服务定位器的工厂接口和类,根据以下产品代码创建ProductSettingsRepository类:

public interface IProductSettingsRepositoryFactory
{
    ProductSettingsRepository Create(string productCode);
}

public class ProductSettingsRepositoryFactory : IProductSettingsRepositoryFactory
{
    public ProductSettingsRepository Create(string productCode)
    {
        return new ProductSettingsRepository(
            ServiceLocator.Current.GetInstance<ILogWriter>(),
            ServiceLocator.Current.GetInstance<ISecurityFunctionRepository>(),
            ServiceLocator.Current.GetInstance<IProductSettingsManager>(),
            ServiceLocator.Current.GetInstance<IReferenceDataService>(),
            productCode);
    }
}

然后确保使用统一容器注册此工厂,如下所示:

unity_container
   .RegisterType<IProductSettingsRepositoryFactory, ProductSettingsRepositoryFactory>();

然后,您可以像这样使用它:

var factory = ServiceLocator
                   .Current
                   .GetInstance<IProductSettingsRepositoryFactory>();

var productSettingsRepo = factory.Create("my product code");