MEF IOC使用
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使用的更多相关文章
- .net自带的IOC容器MEF使用
IOC能做什么 IoC 不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合.更优良的程序. 控制反转: 将控制权移交给第三方容器 new 操作 依赖注入: 在程序 ...
- 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 ...
- C#/Java 常用轮子 (子文章)(持续更新)
-----> 总文章 入口 C# 框架/类库名称 介绍 Topshelf windows服务框架 Quartz 定时任务框架 NVelocity MVC视图引擎 NPOI 文档读写 Signal ...
- NET 自带IOC容器MEF指初体验
转自:http://www.cnblogs.com/ulex/p/4186881.html IOC容器:工具较多,大体功能都相同,大都需要事先对接口与实现进行配对(通过代码或配置文件),然后由系统自动 ...
- .NET中 MEF应用于IOC
IOC解释 IOC,控制反转的意思.所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B,反正A要用到B,则A依赖于B.所谓反转,你必须理解如果不反转,会怎么着,因为A必须要有B,才可 ...
- .NET自带IOC容器MEF之初体验
.NET自带IOC容器MEF之初体验 本文主要把MEF作为一种IOC容器进行讲解,.net中可用的IOC容器非常多,如 CastleWindsor,Unity,Autofac,ObjectBuil ...
- IOC容器MEF在MVC中的使用
最近想把自己的网站框架用IOC改造下,经过对比,我初步选择autofac,虽然MEF不需要配置,但性能不行,autofac虽然需要自己写自动化注入,但性能非常好. 先分析下各大IOC框架的性能,分两类 ...
- Microsoft实现的IOC DI之 Unity 、Service Locator、MEF
这几个工具的站点 Microsoft Unity http://unity.codeplex.com Service Locator http://commonservicelocator.code ...
- Ioc模式和MEF
IOC模式 Ioc模式(又称DI:Dependency Injection 依赖注射). 分离关注( Separation of Concerns : SOC)是Ioc模式和AOP产生最原始动力,通过 ...
随机推荐
- js一些重点知识总结(二)
第一部分:数据类型转换 1) 数据类型的种类: 数值型number.布尔型(true(1) /false (0)).字符串型(String).空类型(null)(object) 2) 数据类型自动转换 ...
- CentOS安装配置MySql数据库
CentOS版本7.2,MySql版本5.7 1.下载MySql安装源 wget https://dev.mysql.com/get/mysql57-community-release-el7 ...
- Linux下 两台机器文件/文件夹 相互拷贝
Linux下 两台机器文件/文件夹 相互拷贝 设有两台机器 :A:*.101及 B:*.102. 把A下的.temp/var/a.txt拷贝到B机器的/text/目录下: 进入B机器:scp root ...
- Python 文件的处理
简单的读取文件 f.read() 是读取这个文件的所有内容 f.readline() 是读取文件的一行 .write() 会去检查这个文件是否存在,不存在则创建,存在的话,则以覆盖的方式将内容写 ...
- NYOJ--21--bfs--三个水杯
/* 输入 第一行一个整数N(0<N<50)表示N组测试数据 接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3> ...
- Luogu [USACO08OPEN]寻宝之路Clear And Present Danger
题目描述 Farmer John is on a boat seeking fabled treasure on one of the N (1 <= N <= 100) islands ...
- [算法题] Remove Element
题目内容 本题来源:LeetCode Given an array and a value, remove all instances of that value in place and retur ...
- C++中加const与不加const的区别
“常量”与“只读变量”的区别. 常量肯定是只读的,例如5, "abc",等,肯定是只读的,因为常量是被编译器放在内存中的只读区域,当然也就不能够去修改它. “只读变量”则是在内存中 ...
- Maven干货2
回顾: 1. maven核心 a) 依赖管理:对jar统一管理.根据坐标(groupId,artifactId,version)去找jar包,本地,私服,中央仓库 b) 项目构建:通过命令构建.cle ...
- Connect By、Level、Start With的使用
--Connect By.Level.Start With的使用 --------------------------------------2013/11/20 Syntax 1 CONNECT B ...