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. 【php】php 连接数据库

    $mysql_server_name=""; //数据库服务器名称 $mysql_username=""; // 连接数据库用户名 $mysql_passwor ...

  2. ionic时间插件ion-datetime-picker

    https://github.com/katemihalikova/ion-datetime-picker

  3. 大数据算法->推荐系统常用算法之基于内容的推荐系统算法

    港真,自己一直非常希望做算法工程师,所以自己现在开始对现在常用的大数据算法进行不断地学习,今天了解到的算法,就是我们生活中无处不在的推荐系统算法. 其实,向别人推荐商品是一个很常见的现象,比如我用了一 ...

  4. 读论文系列:Deep transfer learning person re-identification

    读论文系列:Deep transfer learning person re-identification arxiv 2016 by Mengyue Geng, Yaowei Wang, Tao X ...

  5. 再起航,我的学习笔记之JavaScript设计模式03

    我的学习笔记是根据我的学习情况来定期更新的,预计2-3天更新一章,主要是给大家分享一下,我所学到的知识,如果有什么错误请在评论中指点出来,我一定虚心接受,那么废话不多说开始我们今天的学习分享吧! 上一 ...

  6. poj 3253 Fence Repair 优先队列

    poj 3253 Fence Repair 优先队列 Description Farmer John wants to repair a small length of the fence aroun ...

  7. 如何在Linux上使用VIM进行.Net Core开发

    对于在Linux上开发.Net Core的程序员来说, 似乎都缺少一个好的IDE. Windows上有Visual Studio, Mac上有Visual Studio for Mac, 难道Linu ...

  8. Hbase架构与原理

    Hbase架构与原理 HBase是一个分布式的.面向列的开源数据库,该技术来源于 Fay Chang所撰写的Google论文"Bigtable:一个结构化数据的分布式存储系统".就 ...

  9. NYOJ 57 6174问题

    6174问题 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 假设你有一个各位数字互不相同的四位数,把所有的数字从大到小排序后得到a,从小到大后得到b,然后用a-b替 ...

  10. Xmemcached学习笔记

    memcached有三种java客户端 第一种:Com.danga 包下面的memcached,需引入jar(本人用的是memcached-2.5.2.jar 文末附上附件需要的可以下载) 第二种:s ...