为了使用方便,对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. SiteMesh3整合SpringMVC+FreeMarker

    SiteMesh3配置 添加maven依赖 添加filter 配置servlet 添加sitemesh配置文件 decorator示例 SpringMVC.FreeMarker配置(404问题处理) ...

  2. 人机大战之AlphaGo的硬件配置和算法研究

    AlphaGo的硬件配置 最近AlphaGo与李世石的比赛如火如荼,关于第四盘李世石神之一手不在我们的讨论范围之内.我们重点讨论下AlphaGo的硬件配置: AlphaGo有多个版本,其中最强的是分布 ...

  3. 使用Async和Await进行异步编程(C#版 适用于VS2015)

    你可以使用异步编程来避免你的应用程序的性能瓶颈并且加强总体的响应.然而,用传统的技术来写异步应用是复杂的,同时编写,调试和维护都很困难. VS2012介绍了简单的方法,那就是异步编程,它在.Net F ...

  4. iOS---NSAutoreleasePool自动释放原理及详解

    前言:当您向一个对象发送一个autorelease消息时,Cocoa就会将该对象的一个引用放入到最新的自动释放池.它仍然是个正当的对象,因此自动释放池 定义的作用域内的其它对象可以向它发送消息.当程序 ...

  5. Jquery 选择器 详解

    在线文档地址:http://tool.oschina.net/apidocs/apidoc?api=jquery 各种在线工具地址:http://www.ostools.net/ 一.基本选择器 $( ...

  6. ToString()的各种用法(大全)

    常用例子: string str = ""; str = .ToString("N"); //生成 12,3456.00 str = .ToString(&qu ...

  7. 每天一个linux命令(35):ln 命令

    ln是linux中又一个非常重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接.当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在 ...

  8. Java 线程 — ThreadLocal

    ThreadLocal 先来看看ThreadLocal的注释: This class provides** thread-local variables**. These variables diff ...

  9. 新浪微博SDK开发(1):总述

    花了几天时间,消耗了九牛六虎之力,新浪微博大部分API已经封装,但有部分API实在太难封装. 说起这封装,我必须严重地.从人品和技术层面鄙视一下新浪的程序员,实在太菜了.估计菜鸟都被大企业吸收了,菜到 ...

  10. dubbox

    github源码: https://github.com/dangdangdotcom/dubbox maven中央仓: 无 获取分支 git clone -b dubbox-2.8.4 https: ...