Steve
Steve

Reputation: 91

Use Ninject with Azure Mobile Apps Backend

I am trying to figure out how to use Ninject with Azure Mobile Apps Backend. The Mobile Apps Backend is a .Net Web App.

Following the Ninject documentation from the Ninject.Web.Common wiki in the NuGet package section, I believe that I am supposed to get a NinjectWebCommon class in my App_Start folder when I install Ninject.Web.Common.WebHost. I am not getting that and I am not sure I am following the correct instructions. Can anyone point me in the right direction? Thanks.

Upvotes: 0

Views: 67

Answers (1)

Lee Liu
Lee Liu

Reputation: 2091

As we are using Mobile App .NET Backend, it is an OWIN project, not a common ASP.NET MVC project, so it doesn't use HttpApplication as the article mentioned above (in Ninject , NinjectHttpApplication extends HttpApplication).

We can create NinjectWebCommon class under "App_ Start" folder and register our IDependencyResolver in NinjectWebCommon via method RegisterServices(IKernel kernel)

Here is a demo about define an IDependencyResolver with Ninject:

public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernal;

    public NinjectDependencyResolver(IKernel kernalParam)
    {
        kernal = kernalParam;
        AddBindings();
    }
    public object GetService(Type serviceType)
    {
        return kernal.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernal.GetAll(serviceType);
    }

    public void AddBindings()
    {
        kernal.Bind<IValueCalculator>().To<LinqValueCalculator>().InRequestScope();
        kernal.Bind<IDiscountHelper>().To<DefaultDiscountHelper>().WithConstructorArgument("discount", 10m);
        kernal.Bind<IDiscountHelper>().To<FlexibleDiscountHelper>().WhenInjectedInto<LinqValueCalculator>();
    }
}

Register our NinjectDependencyResolver in NinjectWebCommon:

public static class NinjectWebCommon 
{
  。。。
    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        System.Web.Mvc.DependencyResolver.SetResolver(new
            EssentialTools.Infrastructure.NinjectDependencyResolver(kernel));
    }
}

Then we can use DI in our controller constructor:

public class HomeController : Controller
{
    private IValueCalculator calc;

    public HomeController(IValueCalculator calc)
    {
        this.calc = calc;
    }

    //........
} 

Upvotes: 0

Related Questions