什么是Service Locator 模式?

服务定位模式(Service Locator Pattern)是一种软件开发中的设计模式,通过应用强大的抽象层,可对涉及尝试获取一个服务的过程进行封装。该模式使用一个称为"Service Locator"的中心注册表来处理请求并返回处理特定任务所需的必要信息。

场景描述

某类ClassA依赖于服务ServiceA和服务ServiceB,服务的具体类型需在编译时指定。

这种条件下有以下缺点:

  • 尝试替换或更新依赖项,必须更改类的源代码并且重新编译。
  • 依赖项的具体实现必须在编译时可用。
  • 测试该类非常困难,因为类对依赖项有直接的引用,则依赖项不能使用Stub或Mock对象替换。
  • 该类包含用于创建、定位和管理依赖项的重复代码。

设计目标

使用 Service Locator Pattern 来达成以下目标:

  • 把类与依赖项解耦,从而使这些依赖项可被替换或者更新。
  • 类在编译时并不知道依赖项的具体实现。
  • 类的隔离性和可测试性非常好。
  • 类无需负责依赖项的创建、定位和管理逻辑。
  • 通过将应用程序分解为松耦合的模块,达成模块间的无依赖开发、测试、版本控制和部署。

解决方案

创建一个 Service Locator,其包含各服务的引用,并且封装了定位服务的逻辑。在类中使用 Service Locator 来获取所需服务的实例。

Service Locator 模式并不描述如何实例化服务,其描述了一种注册和定位服务的方式。通常情况下,Service Locator 模式与工厂模式(Factory Pattern)和依赖注入模式(Dependency Injection Pattern)等结合使用。

服务定位器应该能够在不知道抽象类的具体类型的情况下定位到服务。例如,它可能会使用字符串或服务接口类型来影射服务,这允许在无需修改类的条件下替换依赖项的具体实现。

实现细节

通常 ServiceLocator 类提供 IServiceLocator 接口的实现单例,并负责管理该实例的创建和访问。ServiceLocator 类提供 IServiceLocator 接口的默认实现,例如 ActivatingServiceLocator 类,可以同时创建和定位服务。

注意事项

在使用 Service Locator 模式之前,请考虑以下几点:

  • 有很多程序中的元素需要管理。
  • 在使用之前必须编写额外的代码将服务的引用添加到服务定位器。
  • 类将对服务定位器有依赖关系。
  • 源代码变的更加复杂和难以理解。
  • 可以使用配置数据来定义运行时的关系。
  • 必须提供服务的实现。因为服务定位器模式将服务消费者与服务提供者解耦,它可能需要提供额外的逻辑。这种逻辑将保证在服务消费者尝试定位服务之前,服务提供者已被安装和注册。

相关模式

  • 依赖注入(Dependency Injection)。这种模式解决了与 Service Locator 模式相同的问题,但它使用不同的方法。
  • 控制反转(Inversion of Control)。Service Locator 模式是这种模式的特殊版本。它将应用程序的传统控制流程反转。它用被调用对象来代替控制过程的调用方。

参考信息

代码示例

Service Locator 的简单实现,使用静态类实现,未使用Singleton设计,仅作Mapping影射。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection; namespace Infrastructure
{
/// <summary>
/// 服务定位器
/// </summary>
public static class ServiceLocator
{
#region Fields private static readonly Dictionary<Type, Type> _mapping
    = new Dictionary<Type, Type>();
private static readonly Dictionary<Type, object> _resources
    = new Dictionary<Type, object>();
private static object _operationLock = new object(); #endregion #region Add /// <summary>
/// 添加注册资源
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
/// <param name="instance">资源实例</param>
public static void Add<TClass>(object instance)
where TClass : class
{
Add(typeof(TClass), instance);
} /// <summary>
/// 添加注册资源
/// </summary>
/// <param name="typeOfInstance">资源类型</param>
/// <param name="instance">资源实例</param>
public static void Add(Type typeOfInstance, object instance)
{
if (typeOfInstance == null)
throw new ArgumentNullException("typeOfInstance");
if (instance == null)
throw new ArgumentNullException("instance"); if (!(typeOfInstance.IsInstanceOfType(instance)))
{
throw new InvalidCastException(
string.Format(CultureInfo.InvariantCulture,
"Resource does not implement supplied interface: {0}",
       typeOfInstance.FullName));
} lock (_operationLock)
{
if (_resources.ContainsKey(typeOfInstance))
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
        "Resource is already existing : {0}", typeOfInstance.FullName));
}
_resources[typeOfInstance] = instance;
}
} #endregion #region Get /// <summary>
/// 查找指定类型的资源实例
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
/// <returns>资源实例</returns>
public static TClass Get<TClass>()
where TClass : class
{
return Get(typeof(TClass)) as TClass;
} /// <summary>
/// 查找指定类型的资源实例
/// </summary>
/// <param name="typeOfInstance">The type of instance.</param>
/// <returns>资源实例</returns>
public static object Get(Type typeOfInstance)
{
if (typeOfInstance == null)
throw new ArgumentNullException("typeOfInstance"); object resource; lock (_operationLock)
{
if (!_resources.TryGetValue(typeOfInstance, out resource))
{
throw new ResourceNotFoundException(typeOfInstance.FullName);
}
} if (resource == null)
{
throw new ResourceNotInstantiatedException(typeOfInstance.FullName);
} return resource;
} /// <summary>
/// 尝试查找指定类型的资源实例
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
/// <param name="resource">资源实例</param>
/// <returns>是否存在指定资源类型的资源实例</returns>
public static bool TryGet<TClass>(out TClass resource)
where TClass : class
{
bool isFound = false; resource = null;
object target; lock (_operationLock)
{
if (_resources.TryGetValue(typeof(TClass), out target))
{
resource = target as TClass;
isFound = true;
}
} return isFound;
} #endregion #region Register /// <summary>
/// 注册类型
/// </summary>
/// <typeparam name="TClass">实体类型,类型限制为有公共无参构造函数</typeparam>
public static void RegisterType<TClass>()
where TClass : class, new()
{
lock (_operationLock)
{
_mapping[typeof(TClass)] = typeof(TClass);
}
} /// <summary>
/// 注册类型
/// </summary>
/// <typeparam name="TFrom">资源类型</typeparam>
/// <typeparam name="TTo">实体类型,类型限制为有公共无参构造函数</typeparam>
public static void RegisterType<TFrom, TTo>()
where TFrom : class
where TTo : TFrom, new()
{
lock (_operationLock)
{
_mapping[typeof(TFrom)] = typeof(TTo);
_mapping[typeof(TTo)] = typeof(TTo);
}
} /// <summary>
/// 是否已注册此类型
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
/// <returns>是否已注册此类型</returns>
public static bool IsRegistered<TClass>()
{
lock (_operationLock)
{
return _mapping.ContainsKey(typeof(TClass));
}
} #endregion #region Resolve /// <summary>
/// 获取类型实例
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
/// <returns>类型实例</returns>
public static TClass Resolve<TClass>()
where TClass : class
{
TClass resource = default(TClass); bool existing = TryGet<TClass>(out resource);
if (!existing)
{
ConstructorInfo constructor = null; lock (_operationLock)
{
if (!_mapping.ContainsKey(typeof(TClass)))
{
throw new ResourceNotResolvedException(
string.Format(CultureInfo.InvariantCulture,
        "Cannot find the target type : {0}", typeof(TClass).FullName));
} Type concrete = _mapping[typeof(TClass)];
constructor = concrete.GetConstructor(
        BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
if (constructor == null)
{
throw new ResourceNotResolvedException(
string.Format(CultureInfo.InvariantCulture,
        "Public constructor is missing for type : {0}", typeof(TClass).FullName));
}
} Add<TClass>((TClass)constructor.Invoke(null));
} return Get<TClass>();
} #endregion #region Remove /// <summary>
/// 移除指定类型的资源实例
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
public static void Remove<TClass>()
{
Teardown(typeof(TClass));
} /// <summary>
/// 移除指定类型的资源实例
/// </summary>
/// <param name="typeOfInstance">资源类型</param>
public static void Remove(Type typeOfInstance)
{
if (typeOfInstance == null)
throw new ArgumentNullException("typeOfInstance"); lock (_operationLock)
{
_resources.Remove(typeOfInstance);
}
} #endregion #region Teardown /// <summary>
/// 拆除指定类型的资源实例及注册映射类型
/// </summary>
/// <typeparam name="TClass">资源类型</typeparam>
public static void Teardown<TClass>()
{
Teardown(typeof(TClass));
} /// <summary>
/// 拆除指定类型的资源实例及注册映射类型
/// </summary>
/// <param name="typeOfInstance">资源类型</param>
public static void Teardown(Type typeOfInstance)
{
if (typeOfInstance == null)
throw new ArgumentNullException("typeOfInstance"); lock (_operationLock)
{
_resources.Remove(typeOfInstance);
_mapping.Remove(typeOfInstance);
}
} #endregion #region Clear /// <summary>
/// 移除所有资源
/// </summary>
public static void Clear()
{
lock (_operationLock)
{
_resources.Clear();
_mapping.Clear();
}
} #endregion
}
}

Service Locator 测试代码

using System;
using Infrastructure; namespace ServiceLocatorTest
{
class Program
{
interface IServiceA
{
string GetData();
} class ServiceA : IServiceA
{
public string GetData()
{
return "This data is from ServiceA";
}
} static void Main(string[] args)
{
ServiceLocator.RegisterType<IServiceA, ServiceA>();
IServiceA serviceA = ServiceLocator.Resolve<IServiceA>();
string data = serviceA.GetData();
Console.WriteLine(data);
Console.ReadKey();
}
}
}

Service Locator 模式的更多相关文章

  1. Atitit。如何实现dip, di ,ioc ,Service Locator的区别于联系

    Atitit.如何实现dip, di ,ioc  ,Service Locator的区别于联系 1. Dip原则又来自于松耦合思想方向1 2. 要实现dip原则,有以下俩个模式1 3. Ioc和di的 ...

  2. 服务定位器(Service Locator)

    服务定位器(Service Locator) 跟DI容器类似,引入Service Locator目的也在于解耦.有许多成熟的设计模式也可用于解耦,但在Web应用上, Service Locator绝对 ...

  3. .NET 服务器定位模式(Service Locator Pattern)——Common Service Locator

    本文内容 场景 目标 解决方案 实现细节 思考 相关模式 更多信息 参考资料 Common Service Locator 代码很简单,它一般不会单独使用,而是作为一个单件模式,与像 .net Uni ...

  4. 【IOC--Common Service Locator】不依赖于某个具体的IoC

    你在你的应用程序应用IoC容器了吗,你是否希望不依赖于某个具体的IoC,微软的模式与实践团队在Codeplex上发布的Common Service Locator.Common Service Loc ...

  5. [Design Pattern] Service Locator Pattern 简单案例

    Service Locator Pattern,即服务定位模式,用于定位不同的服务.考虑到 InitialContext::lookup 的成本比较高,提供了 Cache 类缓存以定位到的服务. 代码 ...

  6. 依赖注入与Service Locator

    为什么需要依赖注入? ServiceUser是组件,在编写者之外的环境内被使用,且使用者不能改变其源代码. ServiceProvider是服务,其类似于ServiceUser,都要被其他应用使用,不 ...

  7. PHP中应用Service Locator服务定位及单例模式

    单例模式将一个对象实例化后,放在静态变量中,供程序调用. 服务定位(ServiceLocator)就是对象工场Factory,调用者对象直接调用Service Locator,与被调用对象减轻了依赖关 ...

  8. Microsoft实现的IOC DI之 Unity 、Service Locator、MEF

    这几个工具的站点 Microsoft Unity  http://unity.codeplex.com Service Locator http://commonservicelocator.code ...

  9. 【转】Understanding Inversion of Control, Dependency Injection and Service Locator Print

    原文:https://www.dotnettricks.com/learn/dependencyinjection/understanding-inversion-of-control-depende ...

随机推荐

  1. 使用Android Studio时so文件打包不到APK中

    1,需要在build中添加如下配置,这是必备的 Android {   sourceSets {       main {           jniLibs.srcDirs = ['libs']   ...

  2. 认识javascript作用域

    JavaScript的作用域链 这是一个非常重要的知识点了,了解了JavaScript的作用域链的话,能帮助我们理解很多‘异常’问题. 下面我们来看一个小例子,前面我说过的声明提前的例子. var n ...

  3. asp.net中WebForm.aspx与类文件分离使用

    第一步:新建一个web项目和类库,新建一个页面和映射类文件: 第二步:在页面中,删除默认映射类,添加服务器控件. 1.更改映射类命名空间: 原: <%@ Page Language=" ...

  4. Delphi Register

    unit Unit1; interface uses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Form ...

  5. ubuntu1404下Apache2.4错误日志error.log路径位置

    首先打开/etc/apache2路径下的apache2.conf文件,找到ErrorLog如下 ErrorLog ${APACHE_LOG_DIR}/error.log 这里{APACHE_LOG_D ...

  6. 如何用.NET创建Windows服务

    我们将研究如何创建一个作为Windows服务的应用程序.内容包含什么是Windows服务,如何创建.安装和调试它们.会用到System.ServiceProcess.ServiceBase命名空间的类 ...

  7. 添加标签2 jquery 和JS

    TAG添加标签 做了个方法方便调用 一.JS版本 <!DOCTYPE html> <html lang="en"> <head> <met ...

  8. Linux 防火墙设置,禁止某个ip访问

    service  iptables  status        查看防火墙状态 service  iptables  start           开启防火墙 service  iptables  ...

  9. Type 类型

    修改 type 类型 UPDATE  wd_order2 SET  info = array_append(info, row(2,100001, now() )::info )  WHERE id_ ...

  10. CSS2简写代码(优化)

    [1]如果CSS属性值为0,那么你不必为其添加单位(如:px/em): 下面是你可能的写法: padding: 10px 5px 0px 0px; 但是你可能这样写: padding: 10px 5p ...