Skip to content

Instantly share code, notes, and snippets.

@darylteo
Created July 5, 2014 08:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darylteo/5a6b3656cedac556c83b to your computer and use it in GitHub Desktop.
Save darylteo/5a6b3656cedac556c83b to your computer and use it in GitHub Desktop.
Ninject injection into Signalr Hubs with ninject.mvc5.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Ascend.Core.Application.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Ascend.Core.Application.App_Start.NinjectWebCommon), "Stop")]
namespace Ascend.Core.Application.App_Start
{
using System;
using System.Linq;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using Ascend.Core.Application.Services;
using Microsoft.AspNet.SignalR;
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>();
RegisterWithSignalr(kernel);
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterWithSignalr(IKernel kernel)
{
GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(kernel);
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
//
}
private class NinjectSignalRDependencyResolver : DefaultDependencyResolver
{
private readonly IKernel kernel;
public NinjectSignalRDependencyResolver(IKernel kernel)
{
this.kernel = kernel;
}
public override object GetService(Type serviceType)
{
return kernel.TryGet(serviceType) ?? base.GetService(serviceType);
}
public override System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType).Concat(base.GetServices(serviceType));
}
}
}
}