也说Autofac在MVC的简单实践:破解在Controller构造函数中的实例化 - winhu
相信大家对Autofac并不陌生,很多人都在使用。本文只是介绍一下本人在使用时的一点想法总结。
在使用一个框架时,肯定要去它的官网查阅一下。autofac的官网给出了一些经典的使用案例。如注册容器:
var builder = new ContainerBuilder(); // Register individual components
builder.RegisterInstance(new TaskRepository)
.As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now))
.As<ILogger>(); // Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces(); var container = builder.Build();
public class TaskController
{
private ITaskRepository _repository;
private ILogger _logger; // Autofac will automatically find the registered
// values and pass them in for you.
public TaskController(
ITaskRepository repository,
ILogger logger)
{
this._repository = repository;
this._logger = logger;
}
}
在这里先重点说一下在mvc中的使用,如上代码可见,在一个请求到达时,需要对controller进行实例化,而正如autofac官网所说“ If there is more than one constructor on a component type, Autofac will use the constructor with the most resolvable parameters. ”,如果有多个带参构造函数,autofac默认使用参数最多的构造函数。在上面代码中,即便在一个action中,你只用了_ logger ,那么_ repository 也依旧需要被autofac解析。
而在mvc的具体应用中,我们可能会使用多重继承,如下图的结构
在这种情况下,每个controller可能会有很多构造函数,在每个请求到达时,都需要实例化相当一部分的变量。本人没有研究过这种实例化是否会影响效率,只是觉得这样对于开发来讲过于繁琐,且不利于维护,代码也并不流畅。我的想法是在action中,在需要的点去实例化。
经过一些查阅,autofac官方提供了很多库,发现其中Autofac.Mef是可以用另一种方式实现达到同样的效果。文档的介绍只有一句话“ The MEF integration allows you to expose extensibility points in your Autofac applications using the Managed Extensibility Framework . ” mef可能主要用来在对已经开发完毕的版本做补充的时候使用。如某个系统已经开发结束并部署运行了,这时候会有些功能的增加和扩展,在不修改原版本的前提下,使用mef可以将后补充的功能ioc到原系统。mef需要引用ystem.ComponentModel.Composition.dll 库。
先不说别的了,代码说明一切。在接口实现上需要加入ExportAttribute,如:
[Export(typeof(ICustomerBusiService))]
public class CustomerBusiService : ICustomerBusiService
注意,ICustomerBusiService不用做任何的描述,只描述其实现CustomerBusiService即可。为了达到我的目的,我在顶层的controller中增加了一个获取实例的方法,以便action中根据自己的需要获取实例化:
public abstract class AbstractController : Controller
{
private static IAutofacResolver _resolver = new AutofacResolver();
protected T GetService<T>()
{
return _resolver.GetService<T>();
}
}
下面展示一下IAutofacResolver及其实现AutofacResolver
public interface IAutofacResolver
{
T GetService<T>();
} public class AutofacResolver : IAutofacResolver
{
private Autofac.IContainer _container; public T GetService<T>()
{
if (_container == null || !_container.IsRegistered<T>())
{
RegisterPartsFromReferencedAssemblies();
}
return _container.Resolve<T>();
} private void RegisterPartsFromReferencedAssemblies()
{
var asses = BuildManager.GetReferencedAssemblies().Cast<Assembly>();
var assemblyCatalogs = asses.Select(x => new AssemblyCatalog(x));
var catalog = new AggregateCatalog(assemblyCatalogs); var builder = new ContainerBuilder();
builder.RegisterComposablePartCatalog(catalog);
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
}
}
有了这样一个结构,那么在具体的controller中我不需要有构造函数,在acton中只要调用GetService<T>()就可以获取我需要的实例。
public class AccountController : AbstractMvcController
{
[HttpPost]
public ActionResult Register(Customer customer)
{
var ibsCusomter = GetService<ICustomerBusiService>();
ibsCusomter.Register(customer);
return View();
}
}
以上就是全部内容。本文并没有针对复杂的autofac应用进行说明,比如注册复杂的模型,激活事件等。只是对比较简单普遍的autofac的使用进行一些分析,个人认为mvc的站点开发中,不太会用到比较复杂的东西,因为每个用户请求都是独立的,又有并发的问题,所以autofac的单实例也基本不会考虑。
也说Autofac在MVC的简单实践:破解在Controller构造函数中的实例化 - winhu的更多相关文章
- ioc初步理解(二) 简单实用autofac搭建mvc三层+automapper=》ioc(codeFirst)
之前在园子闲逛的时候,发现许多关于automapper的文章,以及用aotufac+automapper合在一起用.当然发现大多数文章是将automapper的特点说出或将automapper几处关键 ...
- 记一次autofac+dapper+mvc的框架搭建实践
1,环境 .net framework4.7.2,Autofac,Autofac.Mvc5,sql server 2,动机 公司项目用的是ef,之前留下代码的大哥,到处using,代码没有分层,连复用 ...
- [转]ASP.NET MVC 4 最佳实践宝典
原文:http://www.cnblogs.com/sonykings/archive/2013/05/30/3107531.html ASP.NET MVC最佳实践 本文档提供了一套旨在帮助创建最佳 ...
- IOC容器-Autofac在MVC中实现json方式注入使用
在你阅读时,默认已经了解IOC和autofac的基本用法, 我在最近的我的博客项目中运用了IOC autofac 实现了依赖注入 由于我的项目时asp.net MVC所以我目前向大家展示MVC中如何使 ...
- 【半小时大话.net依赖注入】(下)详解AutoFac+实战Mvc、Api以及.NET Core的依赖注入
系列目录 上|理论基础+实战控制台程序实现AutoFac注入 下|详解AutoFac+实战Mvc.Api以及.NET Core的依赖注入 前言 本来计划是五篇文章的,每章发个半小时随便翻翻就能懂,但是 ...
- Thrift简单实践
0.什么是RPC RPC(Remote Procedure Call - 远程过程调用),是通过网络从远程计算机上请求服务,而不需要了解底层网路技术的细节.简单点说,就是像调用本地服务(方法)一样调用 ...
- Autofac.Integration.Mvc分析
Autofac.Integration.Mvc static ILifetimeScope LifetimeScope { get { return (ILifetimeScope)HttpConte ...
- Java 异步处理简单实践
Java 异步处理简单实践 http://www.cnblogs.com/fangfan/p/4047932.html 同步与异步 通常同步意味着一个任务的某个处理过程会对多个线程在用串行化处理,而异 ...
- [Solution] 使用Autofac在MVC、Web API、WCF中实现IOC
本来想聊一下面试过程的,1个星期面了6家,4家当场给offer,2家技术通过(1家没下文,1家复试).从中也学习到一些东西,先还是继续Coding吧. 官网:http://autofac.org/ 下 ...
随机推荐
- Linux重启inotify配置max_user_watches无效被恢复默认值8192的正确修改方法
Linux下Rsync+inotify-tools实现数据实时同步中有一个重要的配置就是设置Inotify的max_user_watches值,如果不设置,当遇到大量文件的时候就会出现出错的情况. 一 ...
- FreePlan Windows下默认乱码解决方案
FreePlan 做为一个开源的跨平台的思维导图软件非常好用. 笔者最近在Windows下使用时发现,新建导图文件时默认总是乱码,每次新建元素都需要手动设置一下字体才行. 研究一下,估计是默认模板问题 ...
- Spring Boot 快速入门
Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...
- POJ2004 Mix and build Trie树? dp?
学习Trie树中,所以上网搜一下Trie树的题,找到这个,人家写着是简单dp,那我就想着能学习到什么Trie树上的dp,但最后发现根本好像跟Trie树没有什么联系嘛... 题意就是给你很多个字符串(长 ...
- poj 3735 Training little cats(矩阵快速幂,模版更权威,这题数据很坑)
题目 矩阵快速幂,这里的模版就是计算A^n的,A为矩阵. 之前的矩阵快速幂貌似还是个更通用一些. 下面的题目解释来自 我只想做一个努力的人 @@@请注意 ,单位矩阵最初构造 行和列都要是(猫咪数+1) ...
- HDU 1087 Super Jumping! Jumping! Jumping!(最长上升子序列,dp)
以下引用自:http://www.cnblogs.com/Lyush/archive/2011/08/31/2161314.html沐阳 该题可以算是一道经典的DP题了,题中数据是这样的.以 3 1 ...
- POJ 3641
Pseudoprime numbers Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 6044 Accepted: 24 ...
- POJ 1666
#include<iostream> using namespace std; int main() { int num_stu; int i; ; do{ time=; cin>& ...
- Genymotion加载so出错解决方案
通过网上所搜得出结论: Genymotion是x86的架构,而我们的so库是arm架构的 解决:安装Genymotion-ARM-Translation.zip 1.下载:http://pan.bai ...
- [wikioi]线段树练习 2
http://codevs.cn/problem/1081/ #include <vector> #include <iostream> #include <string ...