MVC Controller Dependency Injection for Beginners【翻译】
|
在codeproject看到一篇文章,群里的一个朋友要帮忙我翻译一下顺便贴出来,这篇文章适合新手,也算是对MEF的一个简单用法的介绍。 Introduction In a simple statement if I want to define an ASP.NET MVC controller then I can say that classes that are responsible for receiving and processing incoming http requests, handling client input, and sending response back to the client. Controllers also act as a coordinator between Model (Business) and View (Presentation). ASP.NET MVC framework itself creates controller objects at run time. There is only one prerequisite, that is controller class must have a parameter less constructor. But if you need to pass some objects with constructor then what will happen? Simply framework will fail to create controller object. In that case we need to create controller objects by our self and inject dependency there. There are many ways you can inject dependency to a class. For example, it might be Property setter,Method, Constructor injection. In this article I will explain how to inject controller dependency to ASP.NET MVC framework with the help of constructor. Without creating custom controller factory inject dependency to controllers are not possible. So I will also explain how to create a very simple custom controller factory and register it to ASP.NET MVC framework. I will also demonstrate a way to inject dependency to controllers using Managed Extensible Framework (MEF). 介绍如果我想用一个简单的声明去定义一个ASP.NET MVC 控制器。然后我会说这个类是负责接收和处理传入的http请求,操作客户端输入,并将响应发送回客户端。Controllers 还可以扮演Model(业务层)和View(表现层)之间的中间人。ASP.NET MVC框架本身在运行时会创建控制器对象。但是有一个前提,那就是控制器类至少必须有一个参数的构造函数。但是,如果你需要传递一些对象给构造函数,那么会发生什么呢?简单的框架,将无法创建控制器对象。在这种情况下,我们需要创建控制器实现自我依赖注入。 有很多方法,你可以注入依赖一类。例如,它可能是物业二传手,方法, 构造函数注入。在这篇文章中,我将解释如何注入控制器的依赖ASP.NET MVC框架的构造函数的帮助。没有创建自定义控制器工厂注入依赖控制器是不可能的。所以,我也将解释如何创建一个非常简单的自定义控制器工厂,并把它注册到ASP.NET MVC框架。我还将展示一种方式来注入依赖使用托管扩展框架(MEF)的控制器。 这里有很多方法可以向类中进行依赖注入。例如,它可能是属性setter方法、构造函数注射。在本文中我将解释向ASP.NETMVC的控制器的使用构造函数辅助进行依赖注入。净MVC框架构造函数的帮助。没有创建自定义控制器工厂注入依赖控制器是不可能的。所以我也会演示如何创建一个非常简单的自定义控制器厂,并把它注册到ASP.NET MVC框架, 我还将演示一种使用托管扩展的框架(MEF)的依赖注入控制器方式。 Why Need to Inject Controller Dependency?In real life application development, you will see almost all ASP.NET MVC applications are needed to inject its dependent component. You can create component directly inside the controller instead of inject them. In that case the controller will be strongly coupled on those components. If any component's implementation is changed or new version of that component is released then you must change controller class itself. Another problem you will face when you will do unit test. You cannot do unit test of those controllers independently (within isolation). You cannot take mocking features from unit testing framework. Without mocking, you cannot do unit test of your code in isolated environment. 在现实生活中的应用程序开发,你会看到,几乎所有的ASP.NET MVC应用程序都需要注入其依赖的组件。您可以在控制器内部创直接建组件对象代替注入。在这种情况下,控制器将被强耦合到这些组件。如果任何组件的实现变更或新版本组件被发布,那么,你必须修改控制器类。当你要做单元测试时,您将面临的另一个问题。 你不能单独对这些控制器类做单元测试。你不能通过单元测试框架实现功能的模拟。没有模拟,你就不能在隔离的环境中做单元测试的代码。 Controller Static StructureASP.NET MVC framework’s controller structure is defined inside an abstract class named Controller. If you want to create any controller, first you will create a class which must be inherited from abstract class 控制器静态结构ASP.NET MVC框架的控制器结构被定义在名为Controller的抽象类。如果你想创建任何控制器,首先您必须必须继承自抽象的Controller类 。Controller类的层次结构的UML类图如下:
All controllers root interface is 所有控制器的根接口 Simple Custom Controller DefinitionIf you create an ASP.NET MVC project, you will get two default controllers. One is 简单的自定义控制器定义如果你创建一个ASP.NET MVC项目时,你会得到两个默认控制器。一个是
If you look at the 如果你查看HomeController中类定义,那么你会发现,这个类没有构造函数。 public class HomeController : Controller We all know that if there is no constructor defined then at compile time .NET Framework creates a default parameter-less constructor. 我们都知道,如果没有构造函数的定义,那么在编译的时候,NET Framework会创建一个默认的无参数的构造函数。 public class HomeController : Controller Still I do not find any place where I can create 我仍然没有找到任何地方,在那里我可以在我的代码库创建DefaultLogger对象,我不是自己创建 HomeController的对象,所以我找不到创建 DefaultLogger对象的地方以及如何传递
HomeController参数给HomeController(ILogger logger)构造函数。如果我生成这个项目,那么,它肯定不会出错。但在运行时将引发异常。 异常详细信息的错误页面将会显示如下:![]() See the stack trace above, object of class
DefaultContollerActivator throw exception named MissingMethodException. If you go MSDN, search the exception which is raised, you will find it there and there clearly mentions “The exception that is thrown when there is an attempt to dynamically access a method that does not exist.” That is the inner exception message. If see next exception named InvalidOperationException, it is actually wrapped MissingMethodException and there you will find more user friendly message and that is “Make sure that the controller has a parameterless public constructor.” If I want to make HomeController workable then I must add a parameter less constructor and framework will create controller object with the help of that constructor. Question will rise how I can pass DefaultLogger object to that controller? Please keep your patience. 查看堆栈跟踪以上,DefaultContollerActivator类的对象 抛出名为MissingMethodException异常 。如果你去MSDN,搜索是谁引发的异常,你会发现它有明确的指出“有一个试图动态访问的方法时不存在引发的异常。”这是内部异常消息。如果看到一个异常名为 InvalidOperationException异常,它实际上是包含MissingMethodException,并且你可以找到更多的友好的提示消息,那就是“确保该控制器具有一个无参数的公共构造函数。”如果我要让 HomeController的可行的话,我必须添加一个无参数的构造函数在框架的帮助下创建控制器对象。问题是,我怎么向控制器传入 DefaultLogger对象?请保持您的耐心。
How MVC Framework Create Controllers?Before start to describe dependency injection process of MVC框架如何创建控制器?开始前描述HomeController的
If you look at the bellow image, you can see that 如果你看看波纹图像,你可以看到, ![]() Why Need Custom Controller Factory?Already you know that Default controller factory creates controller object using parameter less constructor. We can inject our controller by parameterless constructor too. See the code below: 为什么需要自定义控制器工厂?你已经知道,默认控制器工厂创建控制器对象使用无参构造函数。我们可的含参的控制器构造函数实现注入。见下面的代码: public class HomeController : Controller I found many developers who are misguided the way of the above dependency injection process. This is not dependency injection at all. This actually clearly violate the dependency inversion principle. The principle say that "High level module should not depend upon the low level module, both should depend on abstraction. Details should depends upon abstraction". In above code HomeController itself create DefaultLogger object. So it directly depends on ILogger implementation (DefaultLogger). If in future another implementation comes of ILogger interface then HomeController code itself need to change. So it is probed that it is not proper way to do. So if we need proper way to inject dependency. We need parameterised constructor, by which we can inject our ILogger component. So current implementation of DefaultControllerFactory does not support this requirement. So we need a new custom controller factory. 我发现许多开发者的错误就是上述依赖注入过程的方式。这根本不是依赖注入。实际上,这显然违反了依赖倒置原则。原则上说,“ 高级别不应依赖于低级别的模块模块,都应该依赖于抽象。细节上都要取决于抽象“。在上面的代码中的HomeController本身创建DefaultLogger对象。因此,它直接取决于ILogger实现(DefaultLogger)。如果在未来有 ILogger接口的另一种实现,那么HomeController的代码本身需要改变。所以这种尝试是不正确的方式。因此,如果我们需要适当的方式进行注入依赖。我们需要含参构造函数,我们可以注入ILogger组件。因此,当前执行的 DefaultControllerFactory 不支持这一要求。因此,我们需要一个新的自定义控制器工厂。创建自定义控制器厂通过实现 public class CustomControllerFactory : IControllerFactory Now at first you need to register 现在首先你需要在Application_Start方法中向MVC框架注册CustomControllerFactory。 public class MvcApplication : System.Web.HttpApplication If you run the application and see that your parameter-less constructor 如果你运行应用程序会看到无参的HomeController构造函数并没有被调用,含参的MVC框架调用。哇!你的问题很容易就解决了。 |
MVC Controller Dependency Injection for Beginners【翻译】的更多相关文章
- [转载][翻译] IoC 容器和 Dependency Injection 模式
原文地址:Inversion of Control Containers and the Dependency Injection pattern 中文翻译版本是网上的PDF文档,发布在这里仅为方便查 ...
- 依赖注入 | Dependency Injection
原文链接: Angular Dependency Injection翻译人员: 铁锚翻译时间: 2014年02月10日说明: 译者认为,本文中所有名词性的"依赖" 都可以理解为 & ...
- C# Ioc ASP.NET MVC Dependency Injection
ASP.NET MVC Dependency Injection 同志们,非常快速的Ioc注册接口和注入Mvc Controller,步骤如下: 安装Unity.Mvc NuGet Package 在 ...
- Dependency Injection in ASP.NET MVC
原文引自http://www.dotnetcurry.com/ShowArticle.aspx?ID=786 1.传统三层结构,相邻两层之间交互: 2.如果使用EntityFramework则View ...
- 【译】Dependency Injection with Autofac
先说下为什么翻译这篇文章,既定的方向是架构,然后为了学习架构就去学习一些架构模式.设计思想. 突然有一天发现依赖注入这种技能.为了使得架构可测试.易维护.可扩展,需要架构设计为松耦合类型,简单的说也就 ...
- 【转】dependency injection 的例子
Dependency Injection in PHP. Create your own DI container. / blog / PHP By my opinion one of the big ...
- asp.net core 系列之Dependency injection(依赖注入)
这篇文章主要讲解asp.net core 依赖注入的一些内容. ASP.NET Core支持依赖注入.这是一种在类和其依赖之间实现控制反转的一种技术(IOC). 一.依赖注入概述 1.原始的代码 依赖 ...
- Ninject学习(一) - Dependency Injection By Hand
大体上是把官网上的翻译下而已. http://www.ninject.90iogjkdcrorg/wiki.html Dependency Injection By Hand So what's Ni ...
- Inversion of Control Containers and the Dependency Injection pattern(转)
In the Java community there's been a rush of lightweight containers that help to assemble components ...
随机推荐
- Maven随记
如何保持依赖的多个jar保持版本一致 在引入依赖的时候常常需要依赖多个独立的模块, 譬如Spring的content, aop等等, 为了保持版本一致, 可以设置<spring.version& ...
- 解决:/bin/bash: mvn: 未找到命令
在终端执行: sudo apt-get install maven
- BZOJ2818 Gcd
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...
- 最简单的JavaScript模板引擎
在小公司待久了感觉自己的知识面很小,最近逛博客园和一些技术网站看大家在说JavaScript模版引擎的事儿,完全没有概念,网上一搜这是08年开始流行起来的...本来以为这是很高深的知识,后来在网上看到 ...
- Effective java读书笔记
2015年进步很小,看的书也不是很多,感觉自己都要废了,2016是沉淀的一年,在这一年中要不断学习.看书,努力提升自己 计在16年要看12本书,主要涉及java基础.Spring研究.java并发.J ...
- ArcGIS Server开发教程系列(7)使用ArcGIS API for Javascript-Hello World
ArcGIS API for Javascript API下载地址:http://support.esrichina-bj.cn/2011/0223/960.html 选择最新的下载就好了,目前是3 ...
- C#直接赋值和反射赋值(无GC)的性能比较
using System; using System.Reflection; using System.Diagnostics; using System.Runtime.InteropService ...
- ETL简介
1.ETL的定义 ETL分别是“Extract”.“ Transform” .“Load”三个单词的首字母缩写也就是“抽取”.“转换”.“装载”,但我们日常往往简称其为数据抽取. ETL是BI/DW( ...
- Java Persistence with Hibernate
我们在Java中谈到持久化时,一般是指利用SQL在关系数据库中存储数据. ORM映射元数据,JPA支持XML和JDK 5.0注解两种元数据的形式,元数据描述对象和表之间的映射关系, 框架据此将实体对象 ...
- JMS开发步骤和持久化/非持久化Topic消息
------------------------------------------------ 开发一个JMS的基本步骤如下: 1.创建一个JMS connection factory 2.通过co ...









