class ServicesManager : IServiceProvider { private static readonly ServicesManager INSTANCE = new ServicesManager(); public static ServicesManager Instance { get { return INSTANCE; } } private readonly Dictionary<Type, object> _serviceMap = new Dictionary<Type, object>(); public void AddService<T>(T service) { _serviceMap.Add(typeof(T), service); } public object GetService(Type serviceType) { return _serviceMap[serviceType]; } public void Init() { UserCenterService userCenterService = new UserCenterService(this); userCenterService.Init(); AddService<IUserCenterService>(userCenterService); // ... } }在Init方法中依次初始化各个Service对象,构造方法中注意传递this参数(将最为服务提供者),通过AddService泛型方法将各实例添加到容器中 每个Service均从抽象类型ServiceBase派生,基类ServiceBase维护一个IServiceProvider类型的字段_serviceProvider,引用实际的ServicesManager对象 ServiceBase的实现大致如下
abstract class ServiceBase { private readonly IServiceProvider _serviceProvider; protected ServerServiceBase(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } protected T GetService<T>() where T : class { return _serviceProvider.GetService(typeof(T)) as T; } }在各Service内部,可以使用方式如下获取其他Service实例
var realtimeDataService = GetService<IRealtimeDataService>(); realtimeDataService.xxxx