Created
April 18, 2012 22:55
-
-
Save bradwilson/2417226 to your computer and use it in GitHub Desktop.
Ninject dependency resolver for Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics.Contracts; | |
using System.Web.Http.Dependencies; | |
using Ninject; | |
using Ninject.Syntax; | |
public class NinjectDependencyScope : IDependencyScope | |
{ | |
private IResolutionRoot resolver; | |
internal NinjectDependencyScope(IResolutionRoot resolver) | |
{ | |
Contract.Assert(resolver != null); | |
this.resolver = resolver; | |
} | |
public void Dispose() | |
{ | |
IDisposable disposable = resolver as IDisposable; | |
if (disposable != null) | |
disposable.Dispose(); | |
resolver = null; | |
} | |
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 IKernel kernel; | |
public NinjectDependencyResolver(IKernel kernel) | |
: base(kernel) | |
{ | |
this.kernel = kernel; | |
} | |
public IDependencyScope BeginScope() | |
{ | |
return new NinjectDependencyScope(kernel.BeginBlock()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment