Created
October 24, 2015 20:07
-
-
Save martinsteel/e97b3e00d88f26ff78a8 to your computer and use it in GitHub Desktop.
Ninject 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
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; | |
} | |
} |
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.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; | |
} | |
} | |
} |
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.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