1
votes

I'm using Ninject for dependency injection in my ASP.NET Web Api 2 project. Everything is working perfectly locally through Visual Studio and IIS Express, but when I deploy to IIS, the dependency's are not resolved. Below is my Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var webApiConfiguration = new HttpConfiguration();
        webApiConfiguration.EnableCors();
        webApiConfiguration.SuppressDefaultHostAuthentication();
        webApiConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        webApiConfiguration.MapHttpAttributeRoutes();

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

        ConfigureAuth(app);

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Welcome to Web API");
        });
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        kernel.Load(new CourseModule(), new DataPullModule(), new DegreeModule(), new ResponseModule(), new RestSharpModule());

        return kernel;
    }
}

The error I get is when trying to access one of my controllers is below:

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

Here is my constructor for the DegreeController:

    public DegreeController(IDegreeMapper degreeMapper, IDegreeRepository degreeRepository)
    {
        _degreeMapper = degreeMapper;
        _degreeRepository = degreeRepository;
    }

And here is the DegreeModule where I bind interfaces to classes.

public class DegreeModule : NinjectModule
{
    public override void Load()
    {
        Bind<IDegreeController>().To<DegreeController>().InRequestScope();
        Bind<IDegreeMapper>().To<DegreeMapper>().InRequestScope();
        Bind<IDegreeRepository>().To<DegreeRepository>().InRequestScope();
        Bind<IDegreeRatingCalculator>().To<DegreeRatingCalculator>().InRequestScope();
    }
}
1
Could you show constructors of DegreeController?Win
Edited. Let me know if you want to see more.John Oerter
Does it happen in just one controller or all controllers?Win
You might have already solved this, however, have you tried moving this line app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration); To the end of the method (i.e. after the call to app.Run)Adam

1 Answers

1
votes
var kernel = CreateKernel();
app.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(configuration);