1

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.]

1
  • 4
    You inject repo into the controller constructor. Commented Aug 1, 2017 at 1:41

1 Answer 1

6

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();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.