Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

dependency injection - MVC5, WebAPI2 and Ninject Parameterless constructor error

So I have the exact opposite problem as MVC5, Web API 2 and Ninject

I have a new MVC5/WebAPI2 project, that has both "Controller"s and "ApiControllers".

I'm using the latest unstable version of Ninject.Web.WebAPI with no code changes to NinjectDependencyResolve.cs and Ninject.WebCommom.cs (besides binding my dependency) the ApiController's constructor injection works. However, when I call a MVC Controller I get:

No parameterless constructor defined for this object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is you need a Dependency Resolver for both MVC and WebAPI. Depending on which set of Ninject libraries you use, you only get one of those wired in for you.

i.e. if you use the Ninject.Web.WebAPI library you will need to manually set the MVC resolver:

System.Web.Mvc.DependencyResolver.SetResolver(new NinjectResolver(kernel)); 

(I did this in NinjectWebCommon.cs CreateKernel())

Your Ninject resolver can inherit the interface for both WebAPI and MVC:

public class NinjectResolver : NinjectScope, 
    System.Web.Http.Dependencies.IDependencyResolver, 
    System.Web.Mvc.IDependencyResolver

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...