using Autofac;
using Microsoft.Practices.ServiceLocation;
namespace Core.Common
{
/// <summary>
/// 获取被Autofac注入的实例BeanFactory
/// </summary>
public class BeanFactory
{
/// <summary>
/// 获取Bean
/// </summary>
/// <typeparam name="T">获取的实例类型</typeparam>
/// <returns>获取的实例</returns>
public static T GetBean<T>()
{
try
{
if (System.Web.HttpContext.Current != null)
{
ILifetimeScope scope = System.Web.HttpContext.Current.Items[typeof(ILifetimeScope)] as ILifetimeScope;
if (scope != null)
{
return scope.Resolve<T>();
}
}
}
catch
{
}
return ServiceLocator.Current.GetInstance<T>();
}
/// <summary>
/// 获取Bean
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static object GetBean(System.Type type)
{
try
{
if (System.Web.HttpContext.Current != null)
{
ILifetimeScope scope = System.Web.HttpContext.Current.Items[typeof(ILifetimeScope)] as ILifetimeScope;
if (scope != null)
{
return scope.Resolve(type);
}
}
}
catch
{
}
return ServiceLocator.Current.GetInstance (type) ;
}
}
}