Skip to content

Instantly share code, notes, and snippets.

@martinsteel
Created October 24, 2015 20:07
Show Gist options
  • Save martinsteel/e97b3e00d88f26ff78a8 to your computer and use it in GitHub Desktop.
Save martinsteel/e97b3e00d88f26ff78a8 to your computer and use it in GitHub Desktop.
Ninject web api
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);
// this line
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Ninject.Activation;
using Ninject.Parameters;
using Ninject.Syntax;
namespace Mediaburst.ClockworkWeb
{
public class NinjectDependencyScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectDependencyScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
// IDisposable disposable = (IDisposable)resolutionRoot;
// if (disposable != null) disposable.Dispose();
// resolutionRoot = null;
}
}
}
using System.Web.Http.Dependencies;
using Ninject;
namespace Mediaburst.ClockworkWeb
{
public class NinjectResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel _kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(_kernel);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment