繁体   English   中英

通用静态类作为服务定位器

[英]Generic Static Class as Service Locator

我正在应用游戏编程模式中描述的服务定位器模式,并且想知道可能的通用实现。 以下代码确实有效,但我对使用泛型和静态类感到困惑。

以下C#代码的想法是为应用程序的其他部分提供“全局”服务,仅公开接口而不是完整实现。 使用此方法注册的每个服务在应用程序中只有一个实例,但我希望能够轻松地交换/提供所提供接口的不同实现。

我的问题是:当我使用以下类在我的应用程序中提供不同的服务时,C#如何知道我指的是不同类型的不同服务? 直觉上,我几乎认为静态变量_service将被每个新服务覆盖。

public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}

这是一些用法:

// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();

C#为open类型的每个通用参数组合创建一个单独的闭合类型。
由于泛型参数的每个组合都会创建一个单独的类,调用静态构造函数并为每个类创建自己的成员。 你可以把它们想象成不同的类。

public static class GenericCounter<T>
{
    public static int Count { get; set; } = 0;
}

GenericCounter<int>.Count++;
GenericCounter<int>.Count++;
GenericCounter<string>.Count++;
Console.WriteLine(GenericCounter<double>.Count); // 0
Console.WriteLine(GenericCounter<int>.Count); // 2
Console.WriteLine(GenericCounter<string>.Count); // 1

此代码输出:

0
2
1

例如,在您的情况下,行为将您创建两个单独的类相同:

public static class ServiceLocatorOfIMap
{
    static IMap _service;

    public static IMap GetService()
    {
        return _service;
    }

    public static void Provide(IMap service)
    {
        _service = service;
    }
}

public static class ServiceLocatorOfICamera 
{
    static ICamera _service;

    public static ICamera GetService()
    {
        return _service;
    }

    public static void Provide(ICamera service)
    {
        _service = service;
    }
}

并像这样使用它:

// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocatorForICamera.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocatorForICamera.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocatorForIMap.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocatorForIMap.GetService();

通常,它类似于C#在遇到静态泛型类时所做的事情。

我使用它来处理我不能一直使用依赖注入的情况(比如WebForms),但是我想写一个由DI容器解析的可测试类。

用法看起来像

using(var resolved = new ResolvedService<ISomeService>())
{
    resolved.Service.DoSomething();
}

好处:

  • 您可以使用DI容器来解析和释放资源
  • 它是一次性的,处理导致容器释放资源
  • 它使容器和服务注册不在视线范围内

坏事:

  • 它需要一个静态类,但它也在组合根中,所以它不是太糟糕。
  • 如上所述,它直接取决于温莎。 用任何其他容器替换它很容易。 也许有一天我会把它分开,以便ServiceLocator不会耦合到任何特定的容器。 但是现在改变它是微不足道的。

使用这意味着虽然较大的组件(如.aspx页面)不可测试,但我注入的内容是可测试的。 它只是给了我一个疯狂的想法 - 我可以为WebForms页面编写协调器,这样它们几乎是可测试的。 但希望我永远不需要这样做。

internal class ServiceLocator
{
    private static IWindsorContainer _container;

    internal static void Initialize(IWindsorContainer container)
    {
        _container = container;
    }
    internal static TService Resolve<TService>(string key = null)
    {
        if (_container == null)
        {
            throw new InvalidOperationException(
                "ServiceLocator must be initialized with a container by calling Initialize(container).");
        }
        try
        {
            return string.IsNullOrEmpty(key)
                ? _container.Resolve<TService>()
                : _container.Resolve<TService>(key);
        }
        catch (ComponentNotFoundException ex)
        {
            throw new InvalidOperationException(string.Format("No component for {0} has been registered.", typeof(TService).FullName), ex);
        }
    }

    internal static void Release(object resolved)
    {
        _container.Release(resolved);
    }
}

public class ResolvedService<TService> : IDisposable
{
    private bool _disposed;

    private readonly TService _resolvedInstance;

    public TService Service
    {
        get { return _resolvedInstance; }
    }

    public ResolvedService(string key = null)
    {
        _resolvedInstance = ServiceLocator.Resolve<TService>(key);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~ResolvedService()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        ServiceLocator.Release(_resolvedInstance);
        _disposed = true;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM