服务集合 类 的通用 Getter?

Generic Getter for a collection of Service classes?

我正在 Unity-C# 中构建一个应用程序,其中所有内容都在 MVC 模式的 App class 下引用。一个 App 实例将使用多个服务 class 来执行不同的数据相关的事情,并且所有这些服务 class 都派生自 Service.ServiceAbstract,它只包含一个基本构造函数以及用于引用相关 App 实例的 Getter。

理想情况下,我想要的是让 App 实例自己创建所有服务并将其存储在某种容器中,并有一个 Getter 方法来 return对所请求服务的引用。目前是这样操作的;

private Dictionary<Service.ServiceNames, Service.ServiceAbstract> _services = null;

public Service.ServiceAbstract GetService(Service.ServiceNames serviceName)
{
    return _services[serviceName] as Service.ServiceAbstract;
}

我在这个实现中遇到的问题是双重的;

  1. Service.ServiceNames 是枚举,每次必须创建新服务 class 时都会增加可维护性要求。
  2. 在其中一个服务中检索方法的方法如下所示;

    ((Service.AudioService)[Service.ServiceNames.AUDIO]).DoSomething();

    当我需要将数据从一项服务传递到另一项服务时,这会变得笨拙;

    ((Service.ErrorService)[Service.ServiceNames.ERROR]).CreateErrorPopup(((Service.LocaleService)[Service.ServiceNames.LOCALE]).GetString("GENERIC_ERROR"));

我想要的是某种通用方法,它可以接受要获取的服务类型,然后 return 对该服务的引用,而无需调用者强制转换或使用枚举.我知道 <T> 泛型的存在,但我从来没有用它们创建过东西,而且我不确定存储我的服务然后直接 return 它们的好方法。

您可以使用 Type 而不是 enum。在这种情况下,您可以利用泛型函数和类型转换。

private Dictionary<Type, Service.ServiceAbstract> _services = null;

public T GetService<T>()
{
    return _services[typeof(T)] as T;
}

// And then use

GetService<Service.ErrorService>().CreateErrorPopup(GetService<Service.LocaleService>().GetString("GENERIC_ERROR"));

如果您想使用默认构造函数初始化您的服务,并且 如果 您将不会有并发线程调用 GetService<T>() 您也可以使用此代码,这将有所帮助你不要手动初始化 _services

public T GetService<T>() where T : new()
{
    if(!_services.ContainsKey(typeof(T)))
    {
        _services[typeof(T)] = new T();
    }
    return _services[typeof(T)] as T;
}