/// <summary> /// Get the specified service /// </summary> public object GetService(Type serviceType) { ServiceInstanceInformation candidateService = null; if (this.m_cachedServices?.TryGetValue(serviceType, out candidateService) == false && !this.m_notConfiguredServices.Contains(serviceType)) { lock (this.m_lock) { candidateService = this.m_serviceRegistrations.FirstOrDefault(s => s.ImplementedServices.Contains(serviceType) || serviceType.IsAssignableFrom(s.ServiceImplementer)); if (candidateService == null) // Attempt a load from configuration { var cServiceType = this.m_configuration.ServiceProviders.FirstOrDefault(s => s.Type != null && serviceType.IsAssignableFrom(s.Type)); if (cServiceType != null) { candidateService = new ServiceInstanceInformation(cServiceType.Type, this); this.m_serviceRegistrations.Add(candidateService); } else // Attempt to call the service factories to create it { var created = false; foreach (var factory in this.m_serviceFactories) { // Is the service factory already created? created |= factory.TryCreateService(serviceType, out object serviceInstance); if (created) { candidateService = new ServiceInstanceInformation(serviceInstance, this); this.m_cachedServices.TryAdd(serviceType, candidateService); break; } } if (!created) { this.m_notConfiguredServices.Add(serviceType); } } } if (candidateService != null) { this.m_cachedServices.TryAdd(serviceType, candidateService); } } } return(candidateService?.GetInstance()); }
/// <summary> /// Adds a service provider /// </summary> public void AddServiceProvider(Type serviceType) { lock (this.m_lock) { if (this.m_serviceRegistrations.Any(s => s.ServiceImplementer == serviceType)) { this.m_tracer.TraceWarning("Service {0} has already been registered...", serviceType); } else { this.ValidateServiceSignature(serviceType); var sii = new ServiceInstanceInformation(serviceType, this); this.m_serviceRegistrations.Add(sii); if (typeof(IServiceFactory).IsAssignableFrom(serviceType)) { this.AddServiceFactory(sii.GetInstance() as IServiceFactory); } } this.m_notConfiguredServices.Clear(); } }