为了使用方便,对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. windows批处理总结

    rem echo off 表示之后所有命令行不显示,但命令结果总是会显示的!! 不存在%ROOT_DIR% . %CUR_DIR%的变量 rem @表示命令行不显示当前行,但命令结果总是会显示的!! ...

  2. Node.js与Sails~Model和ORM的持久化

    回到目录 上一讲说了在sails里定义model及相关参数的说明,这一讲主要说一下如何将你的Model持久化到文件,关系数据库和Nosql数据库里,在持久化这点上,sails是统一管理的,它可以在/c ...

  3. php将文件转换成二进制输出[转]

    header( "Content-type: image/jpeg"); $PSize = filesize('1.jpg'); $picturedata = fread(fope ...

  4. paip.python错误解决24

    paip.python错误解决 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.net/attilax ...

  5. 破解Excel密码保护文件

    首先打开vba编辑器,输入代码: Public Sub AllInternalPasswords() ' Breaks worksheet and workbook structure passwor ...

  6. Asp.net WebApi 项目示例(增删改查)

    1.WebApi是什么 ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务.ASP.NET Web API 是一种用于在 .NET ...

  7. iOS 屏幕适配:autoResizing autoLayout和sizeClass

    1. autoResizing autoresizing是苹果早期的ui布局适配的解决办法,iOS6之前完全可以胜任了,因为苹果手机只有3.5寸的屏幕,在加上手机app很少支持横屏,所以iOS开发者基 ...

  8. Js 对 浏览器 的 URL的操作

    下面是一些实例: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...

  9. Android WebView 开发教程

    声明在先:必须在AndroidMainfest.xml 里面声明权限,否则在Java里面编写的所有WebView浏览网页的代码都无法正常使用 <uses-permission android:n ...

  10. Java基础-接口中国特色社会主义的体制中有这样的现象:地方省政府要坚持党的领导和按 照国务院的指示进行安全生产。请编写一个java应用程序描述上述的体制现象。 要求如下: (1)该应用程序中有一个“党中央”接口:CentralPartyCommittee,该接口中 有个“坚持党的领导”方法:void partyLeader() (2)该应用程序中有一个“国务院”抽象类:StateCouncil,

    36.中国特色社会主义的体制中有这样的现象:地方省政府要坚持党的领导和按 照国务院的指示进行安全生产.请编写一个java应用程序描述上述的体制现象. 要求如下: (1)该应用程序中有一个“党中央”接口 ...