为了使用方便,对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. java内部类技术提炼

    创作时间:2016.07.28,2016.07.29 本人qq:992591601,欢迎交流. 参考书籍:<Thinking in Java>.<Effective Java> ...

  2. [常见问题]Project facet Java versin 1.8 is not support.

    发生这个问题的原因是我们的java编译环境(JDK版本),与tomcat运行环境(JDK或JRE版本)不一致导致的. 到eclipse的设置中找到compile项(或右键项目进入),看一下编译环境的J ...

  3. atitit 英文与中文与阿拉伯文的简化解决方案.docx

    atitit 英文与中文与阿拉伯文的简化解决方案.docx 1. 英文与中文与阿拉伯文的简化意义1 2. 简化的主要方法分类2 2.1. 同音替代法(比如o2o)2 2.2. 符号法(比如英文i18n ...

  4. Atitit   图像处理 平滑 也称 模糊, 归一化块滤波、高斯滤波、中值滤波、双边滤波)

    Atitit   图像处理 平滑 也称 模糊, 归一化块滤波.高斯滤波.中值滤波.双边滤波) 是一项简单且使用频率很高的图像处理方法 用途 去噪 去雾 各种线性滤波器对图像进行平滑处理,相关OpenC ...

  5. win2008 强制删除故障集群配置

    在正常删除Cluster 节点之后,再添加节点时,报“节点已经加入群集”,无法加入,注册表信息删除后可正常移除Cluster服务,如下: win2008故障转移群集无法退出节点时 删除注册表中这两个后 ...

  6. iOS-ARC

    1. 本文的主要内容: ARC的本质 ARC的开启与关闭 ARC的修饰符 ARC与Block ARC与Toll-Free Bridging ARC的本质 ARC是编译器(时)特性,而不是运行时特性,更 ...

  7. 每天一个linux命令(12):more命令

    more命令,功能类似 cat ,cat命令是整个文件的内容从上到下显示在屏幕上. more会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会 ...

  8. git查看日志

    git查看日志 git log -n 显示前N条记录 git log -3 退出log命令 直接输入: q git log --stat -n 显示提交的文件的简要的修改统计 $ git log -- ...

  9. ROC曲线与AUC值

    本文根据以下文章整理而成,链接: (1)http://blog.csdn.net/ice110956/article/details/20288239 (2)http://blog.csdn.net/ ...

  10. KendoUI系列:AutoComplete

    1.基本使用 <link href="@Url.Content("~/C ontent/kendo/2014.1.318/kendo.common.min.css" ...