I am trying ninject.mvc5 to do DI on Web API application.
I added ninject and ninject.mvc5 in my main MVC project. I added one class library for Web API controllers and using attribute routing. I was trying to inject an object using Setter Injection on both MVC project and class library. Object properly injected in MVC project whereas it's null in class library.
Below code block is from MVC application where Stage contains correct object.
public class HomeController : Controller
{
[Inject]
public IStage Stage { get; set; }
}
Below code is from class library where its failing.
public class UserController : ApiController
{
[Inject]
public IStage Stage { get; set; }
}
Here are the bindings:
public class WebApiApplication : Ninject.Web.Common.WebHost.NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//RegisterDependencies();
}
protected override IKernel CreateKernel()
{
var kernal = new StandardKernel();
kernal.Load(Assembly.GetExecutingAssembly(),
Assembly.Load("UserLibrary"),
Assembly.Load("StageContracts"),
Assembly.Load("StageLibrary"));
return kernal;
}
}
public class DependencyMapper : NinjectModule
{
public override void Load()
{
this.Bind<IStage>().To<Stage>();
}
}
Not sure what am I missing here. Any help would be much appreciated.
I suspect your
DependencyMapperclass is not being loaded.From the documentation concerning the overload you are using to load assemblies:
For instance:
Make sure to provide the long names when loading assemblies for the kernel.