using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; namespace CY.Infrastructure { /// /// Represents the Service Locator. /// public sealed class ServiceLocator : IServiceProvider { #region Private Fields private readonly IUnityContainer container; #endregion #region Private Static Fields private static readonly ServiceLocator instance = new ServiceLocator(); #endregion #region Ctors /// /// Initializes a new instance of ServiceLocator class. /// private ServiceLocator() { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); container = new UnityContainer(); section.Configure(container); } #endregion #region Public Static Properties /// /// Gets the singleton instance of the ServiceLocator class. /// public static ServiceLocator Instance { get { return instance; } } #endregion #region Private Methods private IEnumerable GetParameterOverrides(object overridedArguments) { List overrides = new List(); Type argumentsType = overridedArguments.GetType(); argumentsType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .ToList() .ForEach(property => { var propertyValue = property.GetValue(overridedArguments, null); var propertyName = property.Name; overrides.Add(new ParameterOverride(propertyName, propertyValue)); }); return overrides; } #endregion #region Public Methods /// /// Gets the service instance with the given type. /// /// The type of the service. /// The service instance. public T GetService() { return container.Resolve(); } /// /// Gets the service instance with the given type by using the overrided arguments. /// /// The type of the service. /// The overrided arguments. /// The service instance. public T GetService(object overridedArguments) { var overrides = GetParameterOverrides(overridedArguments); return container.Resolve(overrides.ToArray()); } /// /// Gets the service instance with the given type by using the overrided arguments. /// /// The type of the service. /// The overrided arguments. /// The service instance. public object GetService(Type serviceType, object overridedArguments) { var overrides = GetParameterOverrides(overridedArguments); return container.Resolve(serviceType, overrides.ToArray()); } #endregion #region IServiceProvider Members /// /// Gets the service instance with the given type. /// /// The type of the service. /// The service instance. public object GetService(Type serviceType) { return container.Resolve(serviceType); } #endregion } }