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

本文介绍如何利用MEF简化构建一个灵活、可测试的ASP.NET MVC应用程序,实现依赖注入,并通过示例代码展示具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面一篇介绍了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 的引用)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值