Skip to content

Instantly share code, notes, and snippets.

@cmcnab
Created February 26, 2014 20:05
Show Gist options
  • Save cmcnab/9237422 to your computer and use it in GitHub Desktop.
Save cmcnab/9237422 to your computer and use it in GitHub Desktop.
Ninject dependency resolver
namespace TestProject.Web.Infrastructure
{
using System.Web.Http.Dependencies;
using Ninject;
public class NinjectResolver : NinjectScope, IDependencyResolver
{
private readonly IKernel kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectScope(this.kernel);
}
}
}
namespace TestProject.Web.Infrastructure
{
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Syntax;
public class NinjectScope : IDependencyScope
{
private readonly IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public object GetService(Type serviceType)
{
return this.resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return this.resolutionRoot.GetAll(serviceType);
}
public void Dispose()
{
// We're not using an explicit scope so don't dispose the kernel.
// See http://stackoverflow.com/a/11357824/7937
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment