您的位置:首页 > 编程语言 > ASP

【ASP.NET】 ASP.NET MVC 3 & MEF 2.0

2012-01-29 02:27 330 查看
前面一篇介绍了ASP.NET MVC3 和 Unity 结合使用的示例,Unity 通过 Register 方法或者配置注入实例,MEF 则是通过 [Import] [Export] 特性绑定依赖。在 MEF 2.0 中当前 dll 中如果在 *.Parts.* 命名空间下的类型会自动作为依赖源。CompositionProvider.AddPartsAssembly 亦可运行时添加依赖对象,非常灵活。通过元数据定义的依赖和通过XML来描述依赖关系是各有利弊,XML方式势必带来配置和维护的学习成本(编码注入是一种写法,配置又是另一种写法),而元数据定义方式使得关系凌乱分散,侵入性也较强。

最新的MEF 2.0 Preview 5 加入了 System.ComponentModel.Composition.Web.Mvc.CodePlex.dll 简化了构建一个灵活的,可测试的ASP.NET MVC应用程序,实现:
1)为Controller提供依赖注入
2)通过定义简单的约定(Import & Export) 识别和配置 MEF Parts(组合)
3)将依赖实例的生存周期映射到Request的生存周期上
4) 简化 ActionFilter 和 ModelBinder 的依赖注入实现

* 目前还没有提供 nuget 的方式,所以只能下载 dll 手动添加:
1) System.ComponentModel.Composition.CodePlex.dll
2) System.ComponentModel.Composition.Web.Mvc.CodePlex.dll
下面来看看示例代码,如何利用MEF实现ASP.NET MVC的IoC



MvcWithMefTest 是 MVC Application,Controller IoC 是目标。GenericRepository 是接口,MvcWithMefTest.Repository 是要注入的依赖。
(GenericRepository 和 Models 的代码,参看我上篇blog:【ASP.NET】ASP.NET MVC 3 & Unity.MVC3 )

1. MvcWithMefTest.Repository 的 Export
using System;
using System.Collections.Generic;
using GenericRepository;
using MvcWithMefTest.Models;
using System.ComponentModel.Composition;
using System.Data.Entity;

namespace MvcWithMefTest.Repository
{
[Export(typeof(IRepository<User>))]
public class UserRepository : DbContextRepository<User>
{
[ImportingConstructor]
public UserRepository([Import("Database")]DbContext context)
: base(context)
{ }
}

public class InjectDbInstance
{
[Export("Database")]
public DbContext Database
{
get
{
return new DbEntities();
}
}
}
}上面的代码可以看到,DbContext 实例通过名称化的 ImportingConstructor 注入。对于构造方法的实例注入,不知道还有没有更好的办法?
虽然用 CompositionBatch.AddExportedValue 可以在 Global.asax 里实例化 DbContext 注入,但是拿不到 CompositionContainer 实例,没法完成最后的注册...
看来有必要再研究下 CompositionProvider 的实现机制。

2. Controller 中的 IRepository Import
public class HomeController : Controller
{
[Import]
GenericRepository.IRepository<User> _userRepository;

public ActionResult Index()
{
var users = _userRepository.GetAll();
return View(users);
}
}

3. Global.asax 里完成 AddPartsAssembly
protected void Application_Start()
{

Database.SetInitializer(new MvcWithMefTest.Models.SampleData());

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

CompositionProvider.AddPartsAssembly(typeof(UserRepository).Assembly);
}
这里  AddPartsAssembly 是通过 typeof(xxx).Assembly 来实现的,完全可以通过 Assembly.LoadFrom / LoadFile 完成实际的物理分离(即 Application 工程不添加 Repository.dll 的引用)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息