user3894984
user3894984

Reputation:

Interface issue in MVC 5 'Cannot create an instance of an interface'

Hi I'm trying to use interfaces in my MVC 5 project with the code below:

public ActionResult Index(IAccountController AccountInterface) 
{
    var DynamicID_DDL = AccountInterface.IDMethod(); 
    var model = new loggedinViewModel
    {
        bIDlistItems = new SelectList(DynamicID_DDL)
    };
    ViewBag.DynamicID_DDL = new List<ID>(DynamicID_DDL);            
    return View(model);
}

&

interface

public interface IAccountController
{
    languageSetting[] languageSettingMethod();
    ID[] IDMethod();
}

However I get the error:

Cannot create an instance of an interface.

Why is this happening and how can I fix it ?

Upvotes: 6

Views: 7533

Answers (2)

JWP
JWP

Reputation: 6963

When MVC controllers are called via some route, the model binder attempts to find the null CTOR of that parameter and initialize that object prior to entering the controller action method. Interfaces cannot be instantiated, as they don't have a null CTOR... You could change the parameter type to a concrete class that implements that interface if you are not concerned with tight coupling.

OR here's example on custom model binding

     public class HomeCustomBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            string title = request.Form.Get("Title");
            string day = request.Form.Get("Day");
            string month = request.Form.Get("Month");
            string year = request.Form.Get("Year");

            return new HomePageModels
            {
                Title = title,
                Date = day + "/" + month + "/" + year
            };
        }
        public class HomePageModels {
            public string Title { get; set; }
            public string Date { get; set; }

        }
    }

Upvotes: 3

Hemant B
Hemant B

Reputation: 140

Create a class which implements the Interface

Public class AccountController: IAccountController
{

    //Interface Methods
}

Use the class as parameter in your action Method

 public ActionResult Index(AccountController Account) 
  {
        //Your Code
  }

Upvotes: 0

Related Questions