1.MEF在MVC中和在WebApi中的初始化,是用区别的,他们分别实现的接口如下:
//WebApi需要实现的接口 System.Web.Http.Dependencies.IDependencyResolver //MVC需要实现的接口 System.Web.Mvc.IDependencyResolver
2.MEF的代码如下:
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Http.Dependencies; namespace Test.Domain.Infrastructure.Ioc { public class MefDependencySolver : System.Web.Http.Dependencies.IDependencyResolver, System.Web.Mvc.IDependencyResolver//: IDependencyResolver { private readonly ComposablePartCatalog _catalog; private const string MefContainerKey = "MefContainerKey"; public MefDependencySolver(ComposablePartCatalog catalog) { _catalog = catalog; } public CompositionContainer Container { get { if (!HttpContext.Current.Items.Contains(MefContainerKey)) { HttpContext.Current.Items.Add(MefContainerKey, new CompositionContainer(_catalog)); } CompositionContainer container = (CompositionContainer)HttpContext.Current.Items[MefContainerKey]; HttpContext.Current.Application["Container"] = container; return container; } } #region IDependencyResolver Members public object GetService(Type serviceType) { string contractName = AttributedModelServices.GetContractName(serviceType); return Container.GetExportedValueOrDefault<object>(contractName); } public IEnumerable<object> GetServices(Type serviceType) { return Container.GetExportedValues<object>(serviceType.FullName); } #endregion /// <summary> /// BeginScope /// </summary> /// <returns></returns> public IDependencyScope BeginScope() { return new MefDependencySolver(_catalog); } public void Dispose() { //ToDo } } }
3.在WebApiConfig.cs文件中,设置MEF的初始化,代码如下:
//初始化MEF配置 DirectoryCatalog catalog = new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath); MefDependencySolver solver = new MefDependencySolver(catalog); config.DependencyResolver = solver;
转自:https://blog.csdn.net/allenwdj/article/details/50509340?t=1484492702237