ASP.NET MVC 4.0控制器和MEF,如何将这两者结合在一起

本文关键字:在一起 结合 MVC NET 控制器 MEF ASP | 更新日期: 2023-09-27 18:22:02

我正在尝试使用MEF创建ASP.NET MVC模块。虽然到目前为止,我在没有MVC的情况下使用MEF没有任何问题,但在导出控制器时,我遇到了一些困难。

我以这种方法为例http://kennytordeur.blogspot.de/2012/08/mef-in-aspnet-mvc-4-and-webapi.html我引入了一个包含控制器的外部dll,使它变得更加复杂。但是,如果我遵循Kenny的想法,那么我需要一个通用接口(比如他的例子中的IMyTest),然而,由于我计划拥有许多控制器,这意味着我将需要太多的接口。最后,看起来我重用了控制器的内部方法,而不是整个控制器。

我在这里发现了一个问题如何将MEF与ASP.NET MVC 4和ASP.NET Web API集成,其中包含了一些代码示例,其中我看到了类似的图片-接口的_contactRepository IContactRepository被导入,然后在视图中重用。

这就是为什么我的问题是,在不使用接口的情况下导出整个控制器是否正常?如何做到这一点?

我发现MEF和ASP.NET之间的联系非常令人困惑,起初互联网上有很多例子,但当我深入研究时,其中大多数都已经过时,不实用,或者太原始,看不出它如何应用于更大的项目。

谢谢!

ASP.NET MVC 4.0控制器和MEF,如何将这两者结合在一起

我在MVC 4中使用了MefContrib和MEF,并使用以下内容将所有内容连接起来。您需要从Global.asax中的Application_Start调用Configure方法,以便在MVC需要处理请求时一切就绪。

using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MefContrib.Hosting.Conventions;
using MefContrib.Web.Mvc;
[assembly: PreApplicationStartMethod( typeof(Core.Web.Initialization.DependencyInjection.RegisterDependencyResolver), "RegisterHttpModule" )]
namespace Core.Web.Initialization.DependencyInjection
{
    public class RegisterDependencyResolver
    {
        public static void RegisterHttpModule()
        {
            // Register the CompositionContainerLifetimeHttpModule HttpModule.
            // This makes sure everything is cleaned up correctly after each request.
            CompositionContainerLifetimeHttpModule.Register();      
        }
        public void Configure()
        {
            // Create MEF catalog based on the contents of ~/bin.
            //
            // Note that any class in the referenced assemblies implementing in "IController"
            // is automatically exported to MEF. There is no need for explicit [Export] attributes
            // on ASP.NET MVC controllers. When implementing multiple constructors ensure that
            // there is one constructor marked with the [ImportingConstructor] attribute.
            var catalog = new AggregateCatalog(
                new DirectoryCatalog( "bin" ),
                new ConventionCatalog( new MvcApplicationRegistry() ) );
            // Tell MVC3 to use MEF as its dependency resolver.
            var dependencyResolver = new CompositionDependencyResolver( catalog );
            DependencyResolver.SetResolver( dependencyResolver );
            // Tell MVC3 to resolve dependencies in controllers
            ControllerBuilder.Current.SetControllerFactory( new DefaultControllerFactory( new CompositionControllerActivator( dependencyResolver ) ) );
            // Tell MVC3 to resolve dependencies in filters
            FilterProviders.Providers.Remove( FilterProviders.Providers.Single( f => f is FilterAttributeFilterProvider ) );
            FilterProviders.Providers.Add( new CompositionFilterAttributeFilterProvider( dependencyResolver ) );
            // Tell MVC3 to resolve dependencies in model validators
            ModelValidatorProviders.Providers.Remove( ModelValidatorProviders.Providers.OfType<DataAnnotationsModelValidatorProvider>().Single() );
            ModelValidatorProviders.Providers.Add( new CompositionDataAnnotationsModelValidatorProvider( dependencyResolver ) );
            // Tell MVC3 to resolve model binders through MEF. Model binders must be decorated with [ModelBinderExport].
            ModelBinderProviders.BinderProviders.Add( new CompositionModelBinderProvider( dependencyResolver ) );
        }
    }
}

此外,您需要将控制器导出到MVC。下面是我如何做到这一点的一个例子:

[Export]
[PartCreationPolicy( CreationPolicy.NonShared )]
public partial class HomeController : ControllerCore
{
    [ImportingConstructor]
    public HomeController( DataContext context, ILogFactory logFactory, ServiceFactory serviceFactory ) : base( context, logFactory, serviceFactory )
    {
    }
    public virtual ActionResult Index()
    {
        return View();
    }
}

希望这能有所帮助!