Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4MVC not passing parameters to base controller so generated code does not build

The problem:

I get the following error when I build:

"'.Controllers.ControllerBase' does not contain a constructor that takes 0 arguments"

My base controller looks like this:

public abstract class ControllerBase : Controller
{
    public CompanyChannel<IAuthorizationService> authorizationServiceClient;
         public ControllerBase(CompanyChannel<IAuthorizationService> authService)
    {
        this.authorizationServiceClient = authService;
    }
}

An example controller that makes use of the Base..

public partial class SearchController : ControllerBase
{
    protected CompanyChannel<IComplaintTaskService> complaintTaskServiceChannel;
    protected IComplaintTaskService taskServiceClient;      

    protected ComplaintSearchViewModel searchViewModel;

    #region " Constructor "

    public SearchController(CompanyChannel<IComplaintTaskService> taskService, CompanyChannel<IAuthorizationService> authService, ComplaintSearchViewModel viewModel)
        : base(authService)
    {
        searchViewModel = viewModel;
        this.complaintTaskServiceChannel = taskService;
        this.taskServiceClient = complaintTaskServiceChannel.Channel;
    }

    #endregion

    public virtual ActionResult Index()
    {
        return View();
    }
}

This seems to be tripping T4MVC.

Should I just not be passing params into the base constructor?

like image 388
David McLean Avatar asked Oct 21 '22 19:10

David McLean


1 Answers

Your abstract class must have a default constructor. When you have any constructors in the subclasses that doesn't call the base class ctor means, compiler will automatically call base class's default ctor, therefore you must have one in base class.

Following demo will be helpful to understand ctor chaining in c#

class Base
{
    public Base()
    {
        Console.WriteLine("Base() called");
    }

    public Base(int x)
    {
        Console.WriteLine("Base(int x) called");
    }
}

class Sub : Base
{
    public Sub()
    {
        Console.WriteLine("Sub() called");     
    }
}

and from within your Main() create

new Sub();

and observe the console output

like image 74
Nasmi Sabeer Avatar answered Oct 27 '22 23:10

Nasmi Sabeer