/// <summary> /// Gets a service. /// </summary> /// <param name="serviceType">The type of the service to be found.</param> /// <param name="ensureExists">If true, will throw an exception if the service is not found.</param> /// <returns>The service instance, if present; null if not (and ensureExists is false).</returns> /// <exception cref="ServiceMissingException">Thrown if ensureExists is true and the service is not found.</exception> public object Get(Type serviceType, bool ensureExists) { Guard.ArgumentNotNull(serviceType, "serviceType"); if (Contains(serviceType, SearchMode.Local)) { object result = locator.Get(new DependencyResolutionLocatorKey(serviceType, null)); DemandAddPlaceholder placeholder = result as DemandAddPlaceholder; if (placeholder != null) { Remove(serviceType); result = Build(placeholder.TypeToCreate, serviceType, null); } return(result); } if (parent != null) { return(parent.Get(serviceType, ensureExists)); } if (ensureExists) { throw new ServiceMissingException(serviceType); } return(null); }
/// <summary> /// Adds a service that will not be created until the first time it is requested. /// </summary> /// <param name="serviceType">The type of service</param> /// <param name="registerAs">The type to register the service as</param> public void AddOnDemand(Type serviceType, Type registerAs) { Guard.ArgumentNotNull(serviceType, "serviceType"); if (registerAs == null) { registerAs = serviceType; } DependencyResolutionLocatorKey key = new DependencyResolutionLocatorKey(registerAs, null); if (locator.Contains(key, SearchMode.Local)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateService, registerAs.FullName)); } DemandAddPlaceholder placeholder = new DemandAddPlaceholder(serviceType); locator.Add(key, placeholder); container.Add(placeholder); }