如何将托管可扩展性框架(MEF) 与 ASP.NET MVC 4 和 ASP.NET Web API 集成到同一个项目中?
考虑一个示例应用程序,其中包含一个 MVC 控制器HomeController
和一个 Web API 控制器ContactController
。两者都有 type 的属性IContactRepository
,它们依赖 MEF 来解决。问题是如何将 MEF 插入 MVC 和 Web API,以便通过 MEF 创建实例。
家庭控制器:
/// <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());
}
}
联系人控制器:
/// <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; }
}