我想使用MEF和asp.net mvc。 我写了下面的控制器工厂:MEF和ASP.NET MVC
public class MefControllerFactory : DefaultControllerFactory
{
private CompositionContainer _Container;
public MefControllerFactory(Assembly assembly)
{
_Container = new CompositionContainer(new AssemblyCatalog(assembly));
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType != null)
{
var controllers = _Container.GetExports<IController>();
var controllerExport = controllers.Where(x => x.Value.GetType() == controllerType).FirstOrDefault();
if (controllerExport == null)
{
return base.GetControllerInstance(requestContext, controllerType);
}
return controllerExport.Value;
}
else
{
throw new HttpException((Int32)HttpStatusCode.NotFound,
String.Format(
"The controller for path '{0}' could not be found or it does not implement IController.",
requestContext.HttpContext.Request.Path
)
);
}
}
}
在Global.asax.cs中我设置我的控制器厂:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory.MefControllerFactory(Assembly.GetExecutingAssembly()));
}
我有一个面积:
[Export(typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller
{
private readonly IArticleService _articleService;
[ImportingConstructor]
public HomeController(IArticleService articleService)
{
_articleService = articleService;
}
//
// GET: /Articles/Home/
public ActionResult Index()
{
Article article = _articleService.GetById(55);
return View(article);
}
}
IArticleService
是接口。
有一个类实现IArticleService
并导出它。
它的工作原理。
这就是我需要与MEF一起工作的一切吗?
如何跳过控制器的设置PartCreationPolicy
和ImportingConstructor
?
我想使用构造函数设置我的依赖关系。
当PartCreationPolicy
丢失了,我得到以下异常:
控制器的单个实例“MvcApplication4.Areas.Articles.Controllers.HomeController”不能被用来处理多个请求。如果自定义控制器工厂正在使用中,请确保它为每个请求创建控制器的新实例。
请记住,asp.net MVC中的MEF在部分信任环境中不太友好。例如,在任何部分信任的情况下,书呆子晚餐MEF样品将会非常壮观。基本上,在部分信任方面,由于部分信任的代码无法访问几个MEF内部,所以在使用MEF的方式方面非常有限。 – 2010-07-08 05:25:18
我决定使用Unity代替MEF。 – 2010-08-15 23:47:12