ASP.NET Web Api 2, Ninject, OWIN, and IIS

635 views Asked by At

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

There are 1 answers

0
George Bratu On
var kernel = CreateKernel();
app.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(configuration);