Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created March 20, 2014 10:57
Show Gist options
  • Save jarrettmeyer/9661349 to your computer and use it in GitHub Desktop.
Save jarrettmeyer/9661349 to your computer and use it in GitHub Desktop.
Ninject Web API Setup
using System;
using System.Diagnostics.Contracts;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Activation.Blocks;
namespace MyProject
{
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private readonly IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel.BeginBlock())
{
Contract.Requires<ArgumentNullException>(kernel != null);
this.kernel = kernel;
}
public bool CanDisposeOfKernel
{
get { return kernel != null && !kernel.IsDisposed; }
}
public IDependencyScope BeginScope()
{
IActivationBlock activationBlock = kernel.BeginBlock();
return new NinjectDependencyScope(activationBlock);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(true);
if (CanDisposeOfKernel)
kernel.Dispose();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
using Ninject.Activation;
using Ninject.Activation.Blocks;
using Ninject.Parameters;
namespace MyProject
{
public class NinjectDependencyScope : IDependencyScope
{
private readonly IActivationBlock activationBlock;
public NinjectDependencyScope(IActivationBlock activationBlock)
{
this.activationBlock = activationBlock;
}
public bool CanDisposeOfActivationBlock
{
get { return activationBlock != null && !activationBlock.IsDisposed; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public object GetService(Type serviceType)
{
return GetServices(serviceType).FirstOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = activationBlock.CreateRequest(serviceType, null, new IParameter[] { }, true, false);
IEnumerable<object> services = activationBlock.Resolve(request);
return services;
}
protected virtual void Dispose(bool isDisposing)
{
if (CanDisposeOfActivationBlock)
activationBlock.Dispose();
}
}
}
@jarrettmeyer
Copy link
Author

I have usually been throwing these two files in my ~/App_Start folder of my application. If I were smarter, I would probably just go ahead and add them to a teeny tiny library so I didn't have to constantly retype them all the damn time.

I have read that I shouldn't be disposing of my IKernel instance in my NinjectDependencyResolver class, because this can really mess up anything being declared with .ToSingleton(). I haven't tested this, so I can't back that claim up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment