IOC介绍

IOC:控制反转,DI:依赖注入。按我的理解应该是一个东西。作用目前我看到的主要是解除各个层之间的强耦合,实现接口分离。MEF优点:

1、net4 自带,无需安装扩展(引用System.ComponentModel.Composition.dll)。

2、0配置:这一点很重要,其实很早以前我就看到过IOC的介绍,但一直没搞明白怎么用(配置太多了),有什么用(虽然介绍了,但是看别人写的代码感觉比直接new还麻烦。),最开始还是在spring中看到的。

使用方法举例

1、DAL中使用接口隔离并导出实现类,注意:一个接口只能有一个实现类,接口代码如下:

    public interface IUserRepository
{
List<UserInfo> GetAllUsers();
}

2、实现接口,并导出为IUserRepository,为了规范代码,防止BLL中出现 IUserRepository repository=new UserRepository();之类的代码,将类改为internal,而不是public。代码如下:

 [Export(typeof(IUserRepository))]
internal class UserRepository : MEFDemo.DAL.IUserRepository
{
public List<UserInfo> GetAllUsers()
{
List<UserInfo> listUsers = new List<UserInfo>()
{
new Model.UserInfo(){UserName="奥巴马",Password=""},
new Model.UserInfo(){UserName="邓小平",Password=""}
};
return listUsers;
}
}

3、在BLL中使用,类上标记为Export,需要注入的属性标记为Import。(属性,Java中成为注解)

[Export(typeof(IUserService))]
internal class UserSerVice : IUserService
{
[Import]
protected IUserRepository UserRepository { get; set; } public List<Model.UserInfo> GetAllUsers()
{ return UserRepository.GetAllUsers();
} public Model.UserInfo ValidateUser(string userName, string password)
{ return UserRepository.GetAllUsers().Where(m => m.UserName == userName && m.Password == password).FirstOrDefault();
} }

4、最后这是最关键的一步:

a、MVC,分两步,第一步实现IDependencyResolver接口,代码如下:

    public class MefDependencySolver : IDependencyResolver
{
private readonly ComposablePartCatalog _catalog;
private const string HttpContextKey = "MefContainerKey"; public MefDependencySolver(ComposablePartCatalog catalog)
{
_catalog = catalog;
} public CompositionContainer Container
{
get
{
if (!HttpContext.Current.Items.Contains(HttpContextKey))
{
HttpContext.Current.Items.Add(HttpContextKey, new CompositionContainer(_catalog));
}
CompositionContainer container = (CompositionContainer)HttpContext.Current.Items[HttpContextKey];
HttpContext.Current.Application["Container"] = container;
return container;
}
} #region IDependencyResolver Members public object GetService(Type serviceType)
{
string contractName = AttributedModelServices.GetContractName(serviceType);
return Container.GetExportedValueOrDefault<object>(contractName);
} public IEnumerable<object> GetServices(Type serviceType)
{
return Container.GetExportedValues<object>(serviceType.FullName);
} #endregion
}

第二步,在Global类的Application_Start中注册,代码如下:

            DirectoryCatalog catalog = new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath);
MefDependencySolver solver = new MefDependencySolver(catalog);
DependencyResolver.SetResolver(solver);

b、如果是在单元测试或者应用程序中使用,需要按以下代码来调用,注意 仅仅是最后一层需要手动的用注入容器构造服务层(最后一层)的对象实例

 [Export]
[TestClass()]
public class UserSerViceTests
{ public UserSerViceTests()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(Directory.GetCurrentDirectory()));
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
CompositionContainer container = new CompositionContainer(catalog); UserService = container.GetExportedValue<IUserService>();
}
protected IUserService UserService { get; set; }
[TestMethod()]
public void ValidateUserTest()
{
UserInfo user = UserService.ValidateUser("admin", "");
Assert.IsNull(user);
} [TestMethod()]
public void GetAllUsersTest()
{ List<UserInfo> listUsers = UserService.GetAllUsers();
Assert.IsFalse(listUsers.Count < );
}
}

最后说明一点,MEF如果有一个地方注入失败,将导致所有的注入都不可用。查找错误的方法请参照微软官方文档。

本文代码来源于http://www.cnblogs.com/guomingfeng/archive/2013/05/19/mvc-overall-design.html,非常的深入浅出,以前总看得云里雾里的,现在基本上知道怎么用了,非常感谢作者的分享。有空我也转载一下作者这个系列的博文。

MEF IOC使用的更多相关文章

  1. .net自带的IOC容器MEF使用

    IOC能做什么 IoC 不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合.更优良的程序. 控制反转: 将控制权移交给第三方容器  new 操作 依赖注入: 在程序 ...

  2. practical system design with mef & mef[ trans from arup.codeplex.com/]

    Practical System Design using MEF MVVM RX MOQ Unit Tests in WPF Posted on May 21, 2015 by Arup Baner ...

  3. C#/Java 常用轮子 (子文章)(持续更新)

    -----> 总文章 入口 C# 框架/类库名称 介绍 Topshelf windows服务框架 Quartz 定时任务框架 NVelocity MVC视图引擎 NPOI 文档读写 Signal ...

  4. NET 自带IOC容器MEF指初体验

    转自:http://www.cnblogs.com/ulex/p/4186881.html IOC容器:工具较多,大体功能都相同,大都需要事先对接口与实现进行配对(通过代码或配置文件),然后由系统自动 ...

  5. .NET中 MEF应用于IOC

    IOC解释 IOC,控制反转的意思.所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B,反正A要用到B,则A依赖于B.所谓反转,你必须理解如果不反转,会怎么着,因为A必须要有B,才可 ...

  6. .NET自带IOC容器MEF之初体验

    .NET自带IOC容器MEF之初体验   本文主要把MEF作为一种IOC容器进行讲解,.net中可用的IOC容器非常多,如 CastleWindsor,Unity,Autofac,ObjectBuil ...

  7. IOC容器MEF在MVC中的使用

    最近想把自己的网站框架用IOC改造下,经过对比,我初步选择autofac,虽然MEF不需要配置,但性能不行,autofac虽然需要自己写自动化注入,但性能非常好. 先分析下各大IOC框架的性能,分两类 ...

  8. Microsoft实现的IOC DI之 Unity 、Service Locator、MEF

    这几个工具的站点 Microsoft Unity  http://unity.codeplex.com Service Locator http://commonservicelocator.code ...

  9. Ioc模式和MEF

    IOC模式 Ioc模式(又称DI:Dependency Injection 依赖注射). 分离关注( Separation of Concerns : SOC)是Ioc模式和AOP产生最原始动力,通过 ...

随机推荐

  1. centos中安装mysql

    一.首先输入指令 rpm -qa|grep mysql 检查操作系统中是否已经安装了MySQL 可以通过 yum list | grep mysql 命令来查看yum上提供的mysql数据库可下载的版 ...

  2. java web 中有效解决中文乱码问题-pageEncoding与charset区别, response和request的setCharacterEncoding 区别

    这里先写几个大家容易搞混的编码设置代码: 在jsp代码中的头部往往有这两行代码 pageEncoding是jsp文件本身的编码contentType的charset是指服务器发送给客户端时的内容编码J ...

  3. 亚马逊AWS EC2云实例AMI安装LNMP环境(1)——Nginx安装

    概括:这里选择亚马逊EC2的Linux AMI实例,该Linux服务器是亚马逊预配置的Linux环境,内置多个YUM源,属于亚马逊首推的稳定Linux服务器.默认登录用户名为ec2-user,执行ro ...

  4. Spring-Framework 源码阅读之@Autowired和AutowiredAnnotationBeanPostProcessor

    今天接下去讲我们的内容,上次的解析了AnnotationBeanUtils这个类的运用和源码.今天主要关注的是Autowired和 AutowiredAnnotationBeanPostProcess ...

  5. sql必知必会-总结篇

    总结: 1.全书总览:数据查询.新增.删除:表的新增.更新操作:视图.存储过程.事务.索引的描述,高级sql功能:约束.触发器.索引 2.特色:术语简明定义,讲述最简单化.简而全面. 3.长进的地方: ...

  6. 利用Apache commons-net 包进行FTP文件和文件夹的上传与下载

    首先声明:这段代码是我在网上胡乱找的,调试后可用. 需要提前导入jar包,我导入的是:commons-net-3.0.1,在网上可以下载到.以下为源码,其中文件夹的下载存在问题:FTPFile[] a ...

  7. JDBC连接数据库的基本步骤

    第一步:注册驱动==>:Class.forName("数据库驱动的完整名称(mysql的数据库驱动名称:com.mysql.jbdc.Driver)"); 第二步:创建一个数 ...

  8. 给定一个无序数组arr,求出需要排序的最短子数组长度。例如: arr = [1,5,3,4,2,6,7] 返回4,因为只有[5,3,4,2]需要排序。

    思路 首先从左往右遍历,然后设定一个Max,如果遍历的过程中array[i]大于Max,则置换Max,若小于Max,则指定 k 记录该位置. 然后再从右往左遍历,设定一个Min,在遍历的过程中arra ...

  9. Java微信开发_02_本地服务器映射外网

    一.工具列表 内网穿透的相关工具有: (1)natapp 官网 :https://natapp.cn/ (2)花生壳 官网:https://console.oray.com/ (2)ngrok 官网: ...

  10. Unity 发布的 WenGL 使用SendMessage传递多个参数

    如果要实现Unity与浏览器的数据交互一般都会采用两种方式 方法一: Application.ExternalCall("SayHello","helloworld&qu ...