2
votes

What is the best practice way for to wire up Ninject with both MVC5 and SignalR?

Ninject recommends having Global.asax inherit NinjectHttpApplication and implementing a CreateKernal method:

//Global.asax ([Ninject MVC Website Guidance][1])
protected override IKernel CreateKernel()
{
  var kernel = new StandardKernel(new NinjectRegistrations());
  var ninjectResolver = new CustomNinjectDependencyResolver(kernel);

  DependencyResolver.SetResolver(ninjectResolver); // MVC
  GlobalConfiguration.Configuration.DependencyResolver = ninjectResolver; // Web API

  return kernel;
}

SignalR would like us to use their OwinStartup class register a NinjectDependencyResolver:

//OWIN Startup ([ASP.Net Website Guidance][2])
public void Configuration(IAppBuilder app)
{
  var kernel = new StandardKernel();
  var resolver = new NinjectSignalRDependencyResolver(kernel);  

  var config = new HubConfiguration();
  config.Resolver = resolver;
  Microsoft.AspNet.SignalR.StockTicker.Startup.ConfigureSignalR(app, config);
}

IKernel and NinjectDependencyResolver are needed in both these locations. One option is to start using Static singletons for these, but this does not seem in the spirit of the loose coupling we are shooting for by using Ninject in the first place.

Thanks for any pointers!

1
Don't follow that guidance, it's old. Just install Ninject.MVC5, ninject will configure itself. Follow Anders advice below (but use Ninject.MVC5 instead of MVC3, although MVC3 will work as well).Erik Funkenbusch
Cool, didn't know they got around to upgrade the packageAnders

1 Answers

3
votes

You only need to call MapSignalR from Owin configuration. The Ninject MVC pipeline uses WebActivator to activate Ninject, install package Ninject.MVC5.

Look here how to add SignalR to Ninject startup

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Demo.MVC4/App_Start/NinjectWebCommon.cs#L45