asp.net-mvc – 如何将MEF与ASP.NET MVC 4和ASP.NET Web API集成

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何将MEF与ASP.NET MVC 4和ASP.NET Web API集成前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在同一个项目中集成 Managed Extensibility Framework(MEF)与ASP.NET MVC 4和ASP.NET Web API?

考虑一个示例应用程序,一个MVC控制器HomeController和一个Web API控制器ContactController。两者都有属性类型IContactRepository,他们依靠MEF来解决。问题是如何将MEF插入MVC和Web API,以便通过MEF创建实例。

HomeController:

/// <summary>
/// Home controller. Instruct MEF to create one instance of this class per importer,/// since this is what MVC expects.
/// </summary>
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller
{
    [Import]
    private IContactRepository _contactRepository = null;

    public ActionResult Index()
    {
        return View(_contactRepository.GetAllContacts());
    }
}

ContactController:

/// <summary>
/// Contact API controller. Instruct MEF to create one instance of this class per importer,/// since this is what Web API expects.
/// </summary>
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ContactController : ApiController
{
    [Import]
    private IContactRepository _contactRepo = null;

    public Contact[] Get()
    {
        return _contactRepo.GetAllContacts();
    }
}

IContactRepository和ContactRepository:

public interface IContactRepository
{
    Contact[] GetAllContacts();
}

[Export(typeof(IContactRepository))]
public class ContactRepository : IContactRepository
{
    public Contact[] GetAllContacts()
    {
        return new Contact[] {
            new Contact { Id = 1,Name = "Glenn Beck"},new Contact { Id = 2,Name = "Bill O'Riley"}
        };
    }
}

联系:

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
}

解决方法

解决方案是实现 System.Web.Mvc.IDependencyResolverSystem.Web.Http.Dependencies.IDependencyResolver,并在Application_Start方法中分别注册您的实现与ASP.NET MVC和ASP.NET Web API。

在这个例子中,我们将创建一个类MefConfig,它实现一个方法RegisterMef从Application_Start调用,以安装我们的依赖解析器。类MefDependencyResolver实现System.Web.Mvc.IDependencyResolver和System.Web.Http.Dependencies.IDependencyResolver,因此,处理对MVC和Web API的依赖关系解析职责。

Application_Start,把它放在你的Global.asax.cs中:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        [...]
        MefConfig.RegisterMef();
    }
}

MefDependencyResolver和MefConfig:

/// <summary>
/// Resolve dependencies for MVC / Web API using MEF.
/// </summary>
public class MefDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver,System.Web.Mvc.IDependencyResolver
{
    private readonly CompositionContainer _container;

    public MefDependencyResolver(CompositionContainer container)
    {
        _container = container;
    }

    public IDependencyScope BeginScope()
    {
        return this;
    }

    /// <summary>
    /// Called to request a service implementation.
    /// 
    /// Here we call upon MEF to instantiate implementations of dependencies.
    /// </summary>
    /// <param name="serviceType">Type of service requested.</param>
    /// <returns>Service implementation or null.</returns>
    public object GetService(Type serviceType)
    {
        if (serviceType == null)
            throw new ArgumentNullException("serviceType");

        var name = AttributedModelServices.GetContractName(serviceType);
        var export = _container.GetExportedValueOrDefault<object>(name);
        return export;
    }

    /// <summary>
    /// Called to request service implementations.
    /// 
    /// Here we call upon MEF to instantiate implementations of dependencies.
    /// </summary>
    /// <param name="serviceType">Type of service requested.</param>
    /// <returns>Service implementations.</returns>
    public IEnumerable<object> GetServices(Type serviceType)
    {
        if (serviceType == null)
            throw new ArgumentNullException("serviceType");

        var exports = _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        return exports;
    }

    public void Dispose()
    {
    }
}

public static class MefConfig
{
    public static void RegisterMef()
    {
        var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        var container = new CompositionContainer(asmCatalog);
        var resolver = new MefDependencyResolver(container);
        // Install MEF dependency resolver for MVC
        DependencyResolver.SetResolver(resolver);
        // Install MEF dependency resolver for Web API
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }
}

猜你在找的asp.Net相关文章