为了使用方便,对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 的简单的封装重构的更多相关文章

  1. [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例)

    [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例) 踏雁寻花 发表于 2015-8-23 23:31:28 https://www.itsk.com/thread-35 ...

  2. 对bootstrap modal的简单扩展封装

    对bootstrap modal的简单扩展封装 参考自:http://www.muzilei.com/archives/677   注:原文不支持bootstrap新版本,并且居中等存在问题 此段时间 ...

  3. The service ‘xxx’ configured for WCF is not registered with the Autofac container

    最近在使用autofac.wcf时,报如下异常: Exception Details: System.InvalidOperationException: The service 'xxx' conf ...

  4. 一个用python简单的封装了aria2的jsonrpc中adduri的脚本

    aria2是一个十分牛逼的下载神器,有时候项目需要一个很牛逼的下载中间件的话,aria2是一个不错的选择.其中支持jsonrpc和websocket的特性尤其诱人.但是python用起来还是有点不爽, ...

  5. 最新 AFNetworking 3.0 简单实用封装

    AFNetworking 3.0 的到来使我们开发者又方便了许多,话不多说,直接上代码. 1.首先 引入框架AFNetworking框架 GitHub下载地址:https://github.com/A ...

  6. React+Echarts简单的封装套路

    今天我们来介绍一下React中,对Echarts的一个简单的封装. 首先在我们的React项目中,想使用Echart包,首先需要先安装它,安装代码如下,任选一个就可以 cnpm install ech ...

  7. html --- ajax --- javascript --- 简单的封装

    Ajax的简单封装 Ajax的全称是AsynchronousJavaScriptAndXML 如有疑问请参考:http://zh.wikipedia.org/zh-cn/AJAX 以及传智播客的视频教 ...

  8. andriod开发,简单的封装网络请求并监听返回.

    一.为什么封装 因为android 4.0 以后的发送网络请求必须要放到异步线程中,而异步线程必须跟handle合作才能更新主线程中的UI,所以建议用一个类继承handler来异步处理网络请求. 二. ...

  9. 分页简单的封装SSM+easyUi

    public class Page { private int page = 1; //初始页 private int rows = 10; //一页多少行数据 private String q;// ...

随机推荐

  1. linux下目录操作

    1. 常用函数 #include <dirent.h> //open a directory //failed-NULL, other-return a DIR stream DIR *o ...

  2. GUID相关知识

      全局唯一标识符(GUID,Globally Unique Identifier)是一种由算法生成的二进制长度为128位的数字标识符.GUID主要用于在拥有多个节点.多台计算机的网络或系统中.在理想 ...

  3. 将不确定变成确定~Uri文本文件不用浏览器自动打开,而是下载到本地

    回到目录 这个标题有点长,简单来说就是,对于一个文件下载来说,是否可以提示用户,让它去保存,而不是将它在浏览器中打开,在浏览器中打开有个致命问题,那就是,如果你的页面编码和文件的编码不一致时,打开的就 ...

  4. css自适应宽高等腰梯形

    t1是梯形, ct是梯形里面的内容. 梯形的高度会随着内容的高度撑高.宽度随着浏览器窗口变宽. 梯形上窄下宽或上宽下窄可以通过 transform 的大小来修改. <div class=&quo ...

  5. Atitit blend mode COLOR_DODGE 混合模式  “颜色减淡”模式

    Atitit blend mode COLOR_DODGE 混合模式  "颜色减淡"模式 1.1. 混合模式是图像处理技术中的一个技术名词1 1.2. 目录1 1.3. 颜色减淡C ...

  6. Atitit 图像清晰度 模糊度 检测 识别 评价算法 原理

    Atitit 图像清晰度 模糊度 检测 识别 评价算法 原理 1.1. 图像边缘一般都是通过对图像进行梯度运算来实现的1 1.2. Remark: 1 1.3.  1.失焦检测. 衡量画面模糊的主要方 ...

  7. iOS ---Extension编程指南

    当iOS 8.0和OS X v10.10发布后,一个全新的概念出现在我们眼前,那就是应用扩展.顾名思义,应用扩展允许开发者扩展应用的自定义功能和内容,能够让用户在使用其他app时使用该项功能.你可以开 ...

  8. SQL Server排序函数row_number和rank的区别

    SQL Server排序函数row_number和rank的区别 直接看测试结果 declare @table table(name varchar(100),amount int, memo var ...

  9. hibernate(八) Hibernate检索策略(类级别,关联级别,批量检索)详解

    序言 很多看起来很难的东西其实并不难,关键是看自己是否花费了时间和精力去看,如果一个东西你能看得懂,同样的,别人也能看得懂,体现不出和别人的差距,所以当你觉得自己看了很多书或者学了很多东西的时候,你要 ...

  10. hibernate(六) cascade(级联)和inverse关系详解

    序言 写这篇文章之前,自己也查了很多的资料来搞清楚这两者的关系和各自所做的事情,但是百度一搜,大多数博文感觉说的云里雾里,可能博主自己清楚是怎么一回事,但是给一个不懂的人或者一知半解的人看的话,别人也 ...