Autofac Container 的简单的封装重构
为了使用方便,对Autofac container的简单封装,记录如下,备以后用或分享给大家,欢迎讨论!
using Autofac;
using Autofac.Core.Lifetime;
using Autofac.Integration.Mvc; public static class ContainerManager
{
private static IContainer _container; public static void SetContainer(IContainer container)
{
_container = container;
} public static IContainer Container
{
get { return _container; }
} public static T Resolve<T>(string key = "", ILifetimeScope scope = null) where T : class
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
if (string.IsNullOrEmpty(key))
{
return scope.Resolve<T>();
}
return scope.ResolveKeyed<T>(key);
} public static object Resolve(Type type, ILifetimeScope scope = null)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
return scope.Resolve(type);
} public static T[] ResolveAll<T>(string key = "", ILifetimeScope scope = null)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
if (string.IsNullOrEmpty(key))
{
return scope.Resolve<IEnumerable<T>>().ToArray();
}
return scope.ResolveKeyed<IEnumerable<T>>(key).ToArray();
} public static T ResolveUnregistered<T>(ILifetimeScope scope = null) where T : class
{
return ResolveUnregistered(typeof(T), scope) as T;
} public static object ResolveUnregistered(Type type, ILifetimeScope scope = null)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = Resolve(parameter.ParameterType, scope);
if (service == null) throw new ArgumentException("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (ArgumentException)
{ }
}
throw new ArgumentException("在所有的依赖项中,未找到合适的构造函数。");
} public static bool TryResolve(Type serviceType, ILifetimeScope scope, out object instance)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
return scope.TryResolve(serviceType, out instance);
} public static bool IsRegistered(Type serviceType, ILifetimeScope scope = null)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
return scope.IsRegistered(serviceType);
} public static object ResolveOptional(Type serviceType, ILifetimeScope scope = null)
{
if (scope == null)
{
//no scope specified
scope = Scope();
}
return scope.ResolveOptional(serviceType);
} public static ILifetimeScope Scope()
{
try
{
if (HttpContext.Current != null)
return AutofacDependencyResolver.Current.RequestLifetimeScope; //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
}
catch (Exception)
{
//we can get an exception here if RequestLifetimeScope is already disposed
//for example, requested in or after "Application_EndRequest" handler
//but note that usually it should never happen //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
}
}
}
使用方法如下:
/// <summary>
/// IOCConfig
/// </summary>
public class IOCConfig
{
/// <summary>
/// RegisterAll
/// </summary>
public static void RegisterAll()
{
var iocBuilder = new Autofac.ContainerBuilder(); //todo:为了能编译到web目录,并且发布方便,才在web项目中引用repository项目,在代码中不要直接使用之
iocBuilder.RegisterModule<RIS.Infrastructure.RegisterModule>();
iocBuilder.RegisterModule<RIS.Biz.RegisterModule>();
iocBuilder.RegisterModule<RIS.Repository.RegisterModule>(); iocBuilder.Register((c, p) => new WebWorkContext(p.Named<string>("userToken")))
.As<RIS.Biz.Core.IWorkContext>()
.InstancePerLifetimeScope(); iocBuilder.RegisterControllers(Assembly.GetExecutingAssembly()); iocBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //iocBuilder.RegisterModelBinders(Assembly.GetExecutingAssembly());
//iocBuilder.RegisterModelBinderProvider();
//iocBuilder.RegisterModule<AutofacWebTypesModule>();
var config = GlobalConfiguration.Configuration;
iocBuilder.RegisterWebApiFilterProvider(config);
IContainer iocContainer = iocBuilder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(iocContainer);
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(iocContainer)); RIS.Biz.Core.ContainerManager.SetContainer(iocContainer);
}
} // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
// 请访问 http://go.microsoft.com/?LinkId=9394801
/// <summary>
/// MvcApplication
/// </summary>
public class MvcApplication : System.Web.HttpApplication
{
/// <summary>
/// 程序启动入口
/// </summary>
protected void Application_Start()
{
IOCConfig.RegisterAll(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Autofac Container 的简单的封装重构的更多相关文章
- [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例)
[分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例) 踏雁寻花 发表于 2015-8-23 23:31:28 https://www.itsk.com/thread-35 ...
- 对bootstrap modal的简单扩展封装
对bootstrap modal的简单扩展封装 参考自:http://www.muzilei.com/archives/677 注:原文不支持bootstrap新版本,并且居中等存在问题 此段时间 ...
- The service ‘xxx’ configured for WCF is not registered with the Autofac container
最近在使用autofac.wcf时,报如下异常: Exception Details: System.InvalidOperationException: The service 'xxx' conf ...
- 一个用python简单的封装了aria2的jsonrpc中adduri的脚本
aria2是一个十分牛逼的下载神器,有时候项目需要一个很牛逼的下载中间件的话,aria2是一个不错的选择.其中支持jsonrpc和websocket的特性尤其诱人.但是python用起来还是有点不爽, ...
- 最新 AFNetworking 3.0 简单实用封装
AFNetworking 3.0 的到来使我们开发者又方便了许多,话不多说,直接上代码. 1.首先 引入框架AFNetworking框架 GitHub下载地址:https://github.com/A ...
- React+Echarts简单的封装套路
今天我们来介绍一下React中,对Echarts的一个简单的封装. 首先在我们的React项目中,想使用Echart包,首先需要先安装它,安装代码如下,任选一个就可以 cnpm install ech ...
- html --- ajax --- javascript --- 简单的封装
Ajax的简单封装 Ajax的全称是AsynchronousJavaScriptAndXML 如有疑问请参考:http://zh.wikipedia.org/zh-cn/AJAX 以及传智播客的视频教 ...
- andriod开发,简单的封装网络请求并监听返回.
一.为什么封装 因为android 4.0 以后的发送网络请求必须要放到异步线程中,而异步线程必须跟handle合作才能更新主线程中的UI,所以建议用一个类继承handler来异步处理网络请求. 二. ...
- 分页简单的封装SSM+easyUi
public class Page { private int page = 1; //初始页 private int rows = 10; //一页多少行数据 private String q;// ...
随机推荐
- 自制Unity小游戏TankHero-2D(2)制作敌方坦克
自制Unity小游戏TankHero-2D(2)制作敌方坦克 我在做这样一个坦克游戏,是仿照(http://game.kid.qq.com/a/20140221/028931.htm)这个游戏制作的. ...
- 据说每个大牛、小牛都应该有自己的库——Ajax
蹉跎到今天终于要写Ajax部分了,平时工作中除了选择器我用jQuery的最多的就是ajax,所以这部分在自己的框架中必不可少. XMLHttpRequest 我以为对每个使用过Ajax的人来说XMLH ...
- SQL-truncate && delete && drop 的区别
有些人在删除表的所有记录的时候,喜欢这样来——不给DELETE 语句提供WHERE 子句,表中的所有记录都将被删除.但这种方法是不可取的,正确的应该使用 TRUNCATE TABLE tb_name ...
- SQL关联查询总结
employee表: department表: 笛卡儿积: 等值连接: 内连接(和等值连接效果是相同的): 外连接(外连接不仅返回满足条件的记录,还将返回不满足条件的记录)以下是左外连接,右外连接.全 ...
- linux奇技淫巧 2
压缩解压==================================================================================== unzip xx.zi ...
- WebApi系列~按需序列化字段~Hot
回到目录 起初只是一个想法,一次讨论,一个设想,但相信一定可以实现,具体的事情是这样的,有个对外的API项目,它为一些终端设备提供数据,如手机,平板,PC,当然你也可以说它为很多平台提供数据win32 ...
- MyBatis学习总结(四)——解决字段名与实体类属性名不相同的冲突
在平时的开发中,我们表中的字段名和表对应实体类的属性名称不一定都是完全相同的,下面来演示一下这种情况下的如何解决字段名与实体类属性名不相同的冲突. 一.准备演示需要使用的表和数据 CREATE TAB ...
- WPF入门教程系列八——布局之Grid与UniformGrid(三)
五. Grid Grid顾名思义就是“网格”,它的子控件被放在一个一个实现定义好的小格子里面,整齐配列. Grid和其他各个Panel比较起来,功能最多也最为复杂.要使用Grid,首先要向RowDef ...
- WPF入门教程系列七——布局之WrapPanel与StackPanel(二)
三. WrapPanel WrapPanel布局面板将各个控件从左至右按照行或列的顺序罗列,当长度或高度不够是就会自动调整进行换行,后续排序按照从上至下或从右至左的顺序进行. Orientation— ...
- java三大循环:for、while、do...while
1.while和do...while的区别: while 与 do...while之间的区别:如果布尔表达式第一次执行的结果就为false,那么while循环一次也不执行:do...while循环会执 ...