-
-
Save medmondson/8b00da49cbc7037c697c21645963bb5c to your computer and use it in GitHub Desktop.
Using ninject with webapi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//You need to add this line in CreateKernel method of NinjectWebCommon.cs | |
//GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); | |
//Entire class: | |
using System.Web.Http; | |
using gazprom.uk.Services; | |
using Ninject.Web.WebApi; | |
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(gazprom.uk.App_Start.NinjectWebCommon), "Start")] | |
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(gazprom.uk.App_Start.NinjectWebCommon), "Stop")] | |
namespace gazprom.uk.App_Start | |
{ | |
using System; | |
using System.Web; | |
using Microsoft.Web.Infrastructure.DynamicModuleHelper; | |
using Ninject; | |
using Ninject.Web.Common; | |
public static class NinjectWebCommon | |
{ | |
private static readonly Bootstrapper bootstrapper = new Bootstrapper(); | |
/// <summary> | |
/// Starts the application | |
/// </summary> | |
public static void Start() | |
{ | |
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); | |
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); | |
bootstrapper.Initialize(CreateKernel); | |
} | |
/// <summary> | |
/// Stops the application. | |
/// </summary> | |
public static void Stop() | |
{ | |
bootstrapper.ShutDown(); | |
} | |
/// <summary> | |
/// Creates the kernel that will manage your application. | |
/// </summary> | |
/// <returns>The created kernel.</returns> | |
private static IKernel CreateKernel() | |
{ | |
var kernel = new StandardKernel(); | |
try | |
{ | |
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); | |
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); | |
RegisterServices(kernel); | |
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); | |
return kernel; | |
} | |
catch | |
{ | |
kernel.Dispose(); | |
throw; | |
} | |
} | |
/// <summary> | |
/// Load your modules or register your services here! | |
/// </summary> | |
/// <param name="kernel">The kernel.</param> | |
private static void RegisterServices(IKernel kernel) | |
{ | |
kernel.Bind<IAddressLookup>().To<PostCodeAnywhere>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment