Simsons
Simsons

Reputation: 12735

Cannot create an instance of an Interface with Unity

I have my MVC5 Web controller and trying to do a dependency injection using:

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

My Unity configuration looks like following:

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

But when I am navigating to controller, getting error:

[MissingMethodException: Cannot create an instance of an interface.]

Upvotes: 1

Views: 974

Answers (1)

Philipp Grathwohl
Philipp Grathwohl

Reputation: 2836

You should use constructor injection in your controller instead of injecting the instance in your action.

public class PatientsController : Controller
{
   private ISomeRepository _repo;

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

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

Upvotes: 6

Related Questions