Exemplo n.º 1
0
        private T GetService <T>(Type serviceClass, ServiceConfiguration serviceConfiguration = null)
            where T : IServiceModule
        {
            NonNull <Type>(serviceClass, "serviceClass");

            if (serviceInstanceCache.IsCached(serviceClass))
            {
                return((T)serviceInstanceCache.GetCachedInstance(serviceClass));
            }

            // Try to instantiate it
            IServiceModule service = TryToInstantiate(serviceClass);

            if (service == null)
            {
                // There are no services registered for this interface.
                throw new ServiceModuleInstanceNotFoundException(String.Format("No instance has been registered for interface {0}", serviceClass.Name));
            }

            serviceConfiguration = ResolveServiceConfiguration(service, serviceConfiguration);

            if (service.RequiresConfiguration && serviceConfiguration == null)
            {
                throw new ConfigurationNotFoundException(String.Format("No configuration has been found for service {0}", service.Type));
            }

            service.Configure(this, serviceConfiguration);

            serviceInstanceCache.Add <T>(service);

            return((T)service);
        }
        /// <summary>
        /// Returns instance of a service module.
        /// </summary>
        /// <typeparam name="T">service module type</typeparam>
        /// <param name="serviceClass">service module class type</param>
        /// <param name="serviceConfiguration">service configuration</param>
        /// <returns></returns>
        private T GetInstance <T>(Type serviceClass, ServiceConfiguration serviceConfiguration)
            where T : IServiceModule
        {
            Contract.Requires(serviceClass != null);
            if (services.ContainsKey(serviceClass))
            {
                return((T)services[serviceClass]);
            }

            IServiceModule serviceModule = Activator.CreateInstance(serviceClass) as IServiceModule;
            var            serviceCfg    = serviceConfiguration;

            if (serviceCfg == null)
            {
                serviceCfg = GetServiceConfiguration(serviceModule.Type);
            }
            if (serviceCfg == null && serviceModule.RequiresConfiguration)
            {
                throw new ConfigurationNotFoundException($"{serviceModule.Type} not found on " + ConfigFileName);
            }
            serviceModule.Configure(this, serviceCfg);
            services[serviceClass] = serviceModule;
            return((T)serviceModule);
        }