75 lines
1.8 KiB
C#
75 lines
1.8 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// 服务对象定位器
|
|
/// </summary>
|
|
public sealed class ServiceLocator
|
|
{
|
|
#region fields
|
|
#endregion
|
|
private IServiceProvider _autofacServiceProvider = null;
|
|
#region ctor.
|
|
|
|
private ServiceLocator()
|
|
{
|
|
ContainerBuilder builder = new ContainerBuilder();
|
|
builder.RegisterModule<DefaultAutofacModuleRegister>();
|
|
var AutofacContainer = builder.Build();
|
|
_autofacServiceProvider = new AutofacServiceProvider(AutofacContainer);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region properties
|
|
|
|
#region Instance
|
|
private static readonly ServiceLocator s_Instance = new ServiceLocator();
|
|
|
|
/// <summary>
|
|
/// 服务对象定位器实例
|
|
/// </summary>
|
|
public static ServiceLocator Instance
|
|
{
|
|
get { return s_Instance; }
|
|
}
|
|
#endregion
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
#region methods
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// 获取泛型服务对象
|
|
/// </summary>
|
|
/// <typeparam name="T">服务对象的类型</typeparam>
|
|
/// <returns></returns>
|
|
///
|
|
public T GetService<T>()
|
|
{
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|