ninject setter injection in attribute routing Web API

156 Views Asked by At

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.

2

There are 2 best solutions below

0
JuanR On

I suspect your DependencyMapperclass is not being loaded.

From the documentation concerning the overload you are using to load assemblies:

public static Assembly Load(string assemblyString)

assemblyString Type: System.String The long form of the assembly name.

For instance:

string longName = "system, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

Make sure to provide the long names when loading assemblies for the kernel.

0
Manik_trs On

Thanks @JuanR and @NKosi.

Finally, I got solution. Since the project solution contains MVC and Web API both, we have to set DependencyResolver of both types - System.Web.Http.Dependencies.IDependencyResolver, System.Web.Mvc.IDependencyResolver. Below link is the one helped to solve it.

http://blog.developers.ba/simple-way-share-container-mvc-web-api/