Make sure that the controller has a parameterless public constructor error

rest api make sure that the controller has a parameterless public constructor
c# parameterless constructor error
controller' does not have a default constructor
autofac web api parameterless constructor
umbraco make sure that the controller has a parameterless public constructor.
web api controller interface
web api dependency injection
web api controller factory

I have followed this tutorial which has worked great, until I modified my DbContext to have an additional constructor. I am now having issues with the resolution and not sure what to do to fix this. Is there an easy way to force it to grab the parameterless constructor or I am approaching this incorrectly?

DbContext with two constructors:

public class DashboardDbContext : DbContext
{
    public DashboardDbContext() : base("DefaultConnection") { }

    public DashboardDbContext(DbConnection dbConnection, bool owns)
        : base(dbConnection, owns) { }
}

SiteController constructor:

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

Repository:

DashboardDbContext _context;

public DashboardRepository(DashboardDbContext context)
{
    _context = context;
}

UnityResolver code:

public class UnityResolver : IDependencyResolver
{
    private readonly IUnityContainer _container;

    public UnityResolver(IUnityContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = _container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        _container.Dispose();
    }
}

WebApiConfig:

var container = new UnityContainer();
container.RegisterType<IDashboardRepository, DashboardRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);

Error from WebApi Call:

System.InvalidOperationException: An error occurred when trying to create a controller of type 'SiteController'. Make sure that the controller has a parameterless public constructor.

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) 
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) 
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) 
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()

InnerException: System.ArgumentException: Type 'Dashboard.Web.Controllers.SiteController' does not have a default constructor.

at System.Linq.Expressions.Expression.New(Type type) 
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

The tutorial was great and has been working well for me up until I added the second constructor.

What's happening is that you're bitten by this problem. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.

You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.

But of course, the configuration error comes from you adding the second constructor to your DbContext. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.

So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the DbContext. DbContext is a special type that shouldn't be auto-wired. It is a framework type and you should therefore fallback to registering it using a factory delegate:

container.Register<DashboardDbContext>(
    new InjectionFactory(c => new DashboardDbContext())); 

Error: Make sure that the controller has a parameterless public , Make sure that the controller has a parameterless public constructor" When tried to get this version 1.0 Api [ApiVersion("1.0")] pu Make sure that the controller has a parameterless public constructor. Find the solution for the ApiController, but didn't find anything about normal Controller. Created new MVC 4 project from scratch.

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

WebApi Help in error Make sure that the controller has a , Make sure that the controller has a parameterless public constructor." for this i have checked unity config. boostrapper class. but no luck can  Since Unity returns null, Web API will try to create the controller itself, but since it doesn’t have a default constructor it will throw the “Make sure that the controller has a parameterless public constructor” exception. This exception message is misleading and doesn’t explain the real cause.

I had the same issue and I resolved it by making changes in the UnityConfig.cs file In order to resolve the dependency issue in the UnityConfig.cs file you have to add:

public static void RegisterComponents()    
{
    var container = new UnityContainer();
    container.RegisterType<ITestService, TestService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Resolving "make sure that the controller has a parameter less public , Make sure that the controller has a parameterless public constructor. The reason why it is expecting a default (parameterless) constructor is because the IoC Container was unable to resolve all or some of the parameters of the constructor. Say for example, your constructor is as shown below. Make sure that the controller has a parameterless public constructor. Below screen shot is from Fiddler which shows the exception response in more detail. Click on the image to see it more clearly. The reason why it is expecting a default

Sometimes because you are resolving your interface in ContainerBootstraper.cs it's very difficult to catch the error. In my case there was an error in resolving the implementation of the interface I've injected to the api controller. I couldn't find the error because I have resolve the interface in my bootstraperContainer like this: container.RegisterType<IInterfaceApi, MyInterfaceImplementaionHelper>(new ContainerControlledLifetimeManager()); then I've adde the following line in my bootstrap container : container.RegisterType<MyController>(); so when I compile the project , compiler complained and stopped in above line and showed the error.

Make sure that the controller has a parameterless public constructor, For my WebApi project, I ran into the following error. An error occurred when trying to create a controller of type 'TradeDataController'. Make  Make sure that the controller has a parameterless public constructor. Same goes for all other links that takes me to that specific controller any ideas? Not sure how much more info I can give since this is the only information I think I can get a hold off.

I had the same problem. I googled it for two days. At last I accidentally noticed that the problem was access modifier of the constructor of the Controller. I didn’t put the public key word behind the Controller’s constructor.

public class MyController : ApiController
    {
        private readonly IMyClass _myClass;

        public MyController(IMyClass myClass)
        {
            _myClass = myClass;
        }
    }

I add this experience as another answer maybe someone else made a similar mistake.

C# : Web API Parameterless Public Constructor Error, “An error occurred when trying to create a controller of type 'XController'. Make sure that the controller has a parameterless public constructor”. I checked  The default implementation of the IHttpControllerActivator only supports creating controller types with parameterless constructors via Activator.CreateInstance. API versioning does not get involved with nor modify the way that controllers are activated.

WebApi failing to resolve dependencies, An error occurred when trying to create a controller of type 'ApiController'. Make sure that the controller has a parameterless public constructor. We have a mix  Your controller (as posted here) does have a parameterless public constructor. Your real controller probably has another constructor, not posted here, and as a result the default parameterless constructor is not generated. @DominicZukiewicz The inheriting class knows about the constructor in the base class.

An error occurred when trying to create a controller of type , Nop.Plugins.AjaxFilters.Controllers.Catalog7SpikesController'. Make sure that the controller has a parameterless public constructor. Home  From your code, I can see you are using Unity as your IoC Container. IoC Container will handle the initialization of controller class. To make IoC container to create a instance of your controller, your controller class needs to have a parameterless public constructor(aka default constructor). public class EmployeeApiController :

[Solved] Mvc 5 unity dependency injection : whats wrong in my code , Make sure that the controller has a parameterless public constructor error. Posted by: admin November 27, 2017 Leave a comment. Questions: I have followed  Mvc 5 unity dependency injection : whats wrong in my code? Make sure that the controller has a parameterless public constructor.","ExceptionType":"System

Comments
  • The error is telling you that SiteController is what must have a paramertless constructor, not DashboardDbContext.
  • Hi Smith.h.Neil, but it only throws that error when the additional constructor is added to the dbcontext. If I remove that or comment it out (second constructor) it works fine.
  • Can I see the constructor for SiteController?
  • And I'm guessing you're injecting the DbContext into the repository?
  • @scarpacci Are you sure the only change you're making is removing the second constructor from the DbContext? Unless you're somehow bypassing instantiation of your controller by not having the second DbContext constructor, it would make no sense for the error to be dependent on the DbContext's constructors.
  • PLEASE NOTE when you rebuild your project you may reset your login credentials... before trying to apply this solution please: re-build your project, log yourself out, then in again, only then - refresh your page and observe if the problem persist
  • Thank you - these dingleberries on my backend team break a lot of rules with the unity configs. Starting to wonder if that's how every team uses IOC containers.
  • @Dagrooms: Many developers are bit by this, but this is not a problem that exists in all DI Containers. Simple Injector for instance, will always ensure that an expressive error is prompted in case such thing happens. Another good tip: Don't use a custom IDependencyResolver but only use a custom IControllerActivator instead.
  • This is a really important answer. It's very easy to fall into the trap of chasing set-up issues with Unity when seeing Make sure that the controller has a parameterless public constructor. but it's quite possible the dependency is set-up but an exception deep in the bowels has stopped it being resolved.
  • This. A million times! I forgot to add a dependency map to my Ninject configuration.
  • My deep in the bowels exception was a property type of 'string' when it should have been 'DateTime?'. Would not have looked for that had I not seen this answer. Thanks so very much.
  • More like LousyErrorMessageException()
  • What relevant places did you place the log? I ran from debugger but got no exception, even when I checked all CLR exceptions. I had to add manual constructor resolve and only then I got the error. It told me to add Diagnostic to get a usable error, that finally gave me something to work with