using Autofac; using Autofac.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using APT.Infrastructure.Core; namespace APT.Infrastructure.Api { /// /// 服务对象定位器 /// public sealed class ServiceLocator { #region fields #endregion private IServiceProvider _autofacServiceProvider = null; #region ctor. private ServiceLocator() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterModule(); var AutofacContainer = builder.Build(); _autofacServiceProvider = new AutofacServiceProvider(AutofacContainer); } #endregion #region properties #region Instance private static readonly ServiceLocator s_Instance = new ServiceLocator(); /// /// 服务对象定位器实例 /// public static ServiceLocator Instance { get { return s_Instance; } } #endregion #endregion #region methods /// /// 获取泛型服务对象 /// /// 服务对象的类型 /// /// public T GetService() { if (HttpContext.Current != null && HttpContext.Current.RequestServices != null) return (T)HttpContext.Current.RequestServices.GetService(typeof(T)); if (_autofacServiceProvider != null) return (T)_autofacServiceProvider.GetService(typeof(T)); return default(T); } #endregion } }