无法使用 Unity 创建接口实例

Cannot create an instance of an Interface with Unity

我有我的 MVC5 Web 控制器并尝试使用以下方法进行依赖注入:

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

我的 Unity 配置如下所示:

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: 无法创建接口实例。]

您应该在控制器中使用构造函数注入,而不是在操作中注入实例。

public class PatientsController : Controller
{
   private ISomeRepository _repo;

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

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