同じプロジェクトでManaged Extensibility Framework (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; }
}