1

I'm migrating an MVC/WebApi application to using Owin, but after installing all the components, and moving all configuration from the globals.asax to Startup.cs i'm getting the error Type 'EventController' does not have a default constructor.

It seems how i've got ninject configured isn't working correctly. Can anyone spot the error?

EventController

public class EventController : BaseApiController
{
    private readonly IAttendeeService attendeeService;
    private readonly IEventService eventService;
    private readonly IExcelService excelService;

    public EventController(IEventService eventService, IAttendeeService attendeeService, IExcelService excelService)
    {
        this.attendeeService = attendeeService;
        this.eventService = eventService;
        this.excelService = excelService;
    }
}

Here's the startup.cs class

using System.Linq;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Filanthropy.Core;
using Filanthropy.Model.Models;
using Filanthropy.Services;
using Filanthropy.Web;
using Filanthropy.Web.App_Start;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Newtonsoft.Json.Serialization;
using Ninject;
using Ninject.Web.Common;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin;

[assembly: OwinStartup(typeof(Startup))]
namespace Filanthropy.Web
{
    public partial class Startup
    {

        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfig = new HttpConfiguration();

            ConfigureOAuthTokenGeneration(app);

            ConfigureWebApi(httpConfig);

            app.UseCors(CorsOptions.AllowAll);

            app.UseWebApi(httpConfig);

            app.MapSignalR();

            app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(httpConfig);


            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AutoMapperConfig.Configure();
        }

        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(FilanthropyContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here

        }

        private void ConfigureWebApi(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
               );

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        private static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());

            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IDbContext>().To<FilanthropyContext>().InRequestScope();
            kernel.Bind<IEventService>().To<EventService>().InRequestScope();
            kernel.Bind<IAttendeeService>().To<AttendeeService>().InRequestScope();
            kernel.Bind<IProjectService>().To<ProjectService>().InRequestScope();
            kernel.Bind<IPaymentService>().To<PaymentService>().InRequestScope();
            kernel.Bind<IPledgeService>().To<PledgeService>().InRequestScope();
            kernel.Bind<IExcelService>().To<ExcelService>();

            kernel.Bind<IUserStore<ApplicationUser>>()
                .To<UserStore<ApplicationUser>>()
                .WithConstructorArgument("context", context => kernel.Get<FilanthropyContext>());
        }       


    }
}
MrBliz
  • 5,730
  • 14
  • 55
  • 81
  • take a look at [this similar question](http://stackoverflow.com/questions/17462175/mvc-4-web-api-controller-does-not-have-a-default-constructor) – Jonesopolis Jun 20 '15 at 20:19
  • Have you tried putting `app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(httpConfig);` before `app.UseWebApi(httpConfig);`? – Kévin Chalet Jun 21 '15 at 11:36
  • That causes a cyclic dependency error @Pinpoint – MrBliz Jun 21 '15 at 13:24
  • Does this answer your question? [Ninject error in WebAPI 2.1 - Make sure that the controller has a parameterless public constructor](https://stackoverflow.com/questions/24195159/ninject-error-in-webapi-2-1-make-sure-that-the-controller-has-a-parameterless) – Florian Winter Jul 24 '20 at 12:46

2 Answers2

0

You need to tell Ninject how to correctly resolve Web API dependencies.

Edit: NinjectWebCommon.cs and update the CreateKernel() method to include: GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();

    try
    {
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        //Note: Add the line below:
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}
PavanT
  • 81
  • 6
0

I know this is a old thread and have solutions marked as answers, but none of these worked for me and found another solution that worked for me. Posting it for others who still might be facing the problem.

I am using ASP.NET MVC 5 with VS 2017 and Ninject. I implemented all suggestions mentioned in this thread but I was still getting the 'does not have a default constructor' runtime error. I installed Ninject.MVC5 nuget package and it worked.

Balaji Birajdar
  • 2,309
  • 1
  • 22
  • 26