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. tensorflow官方文档中的sub 和mul中的函数已经在API中改名了

    在照着tensorflow 官方文档和极客学院中tensorflow中文文档学习tensorflow时,遇到下面的两个问题: 1)AttributeError: module 'tensorflow' ...

  2. linux下删除文件及文件夹命令

    一.删除空文件与文件夹 rm或rmdir 文件/文件夹 二.删除非空文件与文件夹 rm -rf 文件/文件夹

  3. HashMap遍历和使用

    map的几种遍历方式: Map< String, String> map = new HashMap<>(); map.put("aa", "@s ...

  4. Linux 组配置文件(/etc/group)

    一.概述 Linux 组配置(/etc/group)文件分为4个字段,分别为: 组名.组密码.GID和组成员. 二.示例 用户apple和banana的默认组为fruit. [root@titan ~ ...

  5. WordCount去除标点方法之一

    package com.bw.day10;import java.io.IOException;import java.util.StringTokenizer;import org.apache.h ...

  6. 计蒜客模拟赛D2T1 蒜头君的兔子:矩阵快速幂

    题目链接:https://nanti.jisuanke.com/t/16442 题意: 有个人在第一年送了你一对1岁的兔子.这种兔子刚生下来的时候算0岁,当它在2~10岁的时候,每年都会生下一对兔子, ...

  7. MySQL表空间集

    --MySQL表空间集 ----------------------2014-09-20 1. 收缩ibdata的方法,目前MySQL依然没有提供收缩ibdata的方法,只能重构,下面是5.7的步骤. ...

  8. MyBatis从入门到放弃六:延迟加载、一级缓存、二级缓存

    前言 使用ORM框架我们更多的是使用其查询功能,那么查询海量数据则又离不开性能,那么这篇中我们就看下mybatis高级应用之延迟加载.一级缓存.二级缓存.使用时需要注意延迟加载必须使用resultMa ...

  9. 解析Linux中的VFS文件系统之文件系统的来源与简介(一)

    最近挂载了N多的文件系统,大致了不同文件系统的相应特性及挂载方式,却还是对Linux的文件系统没有从源码方面去了解.不求甚解确实不好不好. 于是借鉴一些大牛的博客及自己的理解,总结了博客系列: 一.V ...

  10. SpringMVC详解(四)------SSM三大框架整合之登录功能实现

    为了后面讲解的需要,我们取数据都会从数据库中获取,所以这里先讲讲三大框架(Spring.SpringMVC.MyBatis)的整合.前面讲解 MyBatis 时,写了一篇 MyBatis 和 Spri ...