【发布时间】:2011-03-03 07:11:03
【问题描述】:
我想将 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 asp.net-mvc mef