1

我有我的MVC5網絡控制器,並試圖用做依賴注入創建一個接口的實例:不能使用Unity

public class PatientsController : Controller 
    { 
     public ISomeRepository _repo; 
     // GET: Patients 
     public ActionResult Index(ISomeRepository repo) 
     { 
      _repo = repo; 
      return View(); 
     } 
    } 

我的統一配置類似以下內容:

public static class UnityConfig 
    { 
     public static void RegisterComponents() 
     { 
      var container = new UnityContainer(); 

      // register all your components with the container here 
      // it is NOT necessary to register your controllers 

      // e.g. container.RegisterType<ITestService, TestService>(); 
      container.RegisterType<ISomeRepository, SomeRepository>(); 

      // GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); 
      GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container); 
     } 

但是,當我正在導航到控制器,出現錯誤:

[MissingMethodException:無法創建接口的實例。]

+4

將'repo'注入到控制器構造函數中。 – Jasen

回答

5

您應該在控制器中使用構造函數注入,而不是在動作中注入實例。

public class PatientsController : Controller 
{ 
    private ISomeRepository _repo; 

    public PatientsController(ISomeRepository repo) 
    { 
     _repo = repo; 
    }   

    public ActionResult Index() 
    { 
     // use _repo here 
     return View(); 
    } 
}