Skip to content

Instantly share code, notes, and snippets.

@cvbarros
Created February 3, 2014 12:56
Show Gist options
  • Save cvbarros/8783363 to your computer and use it in GitHub Desktop.
Save cvbarros/8783363 to your computer and use it in GitHub Desktop.
Ninject Dependency Resolver for WebAPI
public class NinjectDependencyScope : IDependencyScope
{
private readonly IResolutionRoot _resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
_resolver = resolver;
}
public void Dispose()
{
// Don't dispose the kernel, or you'll run into trouble with Scopes and Singletons
}
public object GetService(Type serviceType)
{
if (_resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return _resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (_resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return _resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
//Don't use _kernel.BeginBlock() or you'll run into trouble with Scopes
return new NinjectDependencyScope(_kernel);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment