代码之家  ›  专栏  ›  技术社区  ›  Simsons

无法创建Unity接口的实例

  •  1
  • Simsons  · 技术社区  · 7 年前

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

    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);
            }
    

    但当我导航到控制器时,出现错误:

    1 回复  |  直到 7 年前
        1
  •  6
  •   Philipp Grathwohl    7 年前

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

    public class PatientsController : Controller
    {
       private ISomeRepository _repo;
    
       public PatientsController(ISomeRepository repo) 
       { 
          _repo = repo;
       }        
    
       public ActionResult Index()
       {
          // use _repo here
          return View();
       }
    }