Reputation: 3589
I am wiring up Ninject with MVC4 and have it working to the point it's trying to actually resolve dependencies. However, I am getting the following exception:
Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'.
Anyone ran into this and have a work around?
Upvotes: 2
Views: 2402
Reputation: 1038900
GlobalConfiguration.Configuration.ServiceResolver
was replaced with GlobalConfiguration.Configuration.DependencyResolver
in the RC. So I guess the Ninject package you are using is simply not designed for the RC. It was one of the breaking changes.
So here are the steps to make Ninject work with ASP.NET MVC 4 Web API RC:
Declare an interface:
public interface IFoo
{
string GetBar();
}
Then an implementation:
public class Foo : IFoo
{
public string GetBar()
{
return "the bar";
}
}
Then add an API controller:
public class ValuesController : ApiController
{
private readonly IFoo _foo;
public ValuesController(IFoo foo)
{
_foo = foo;
}
public string Get()
{
return _foo.GetBar();
}
}
Install the Ninject.Mvc3
NuGet package (Install-Package Ninject.Mvc3
)
Define a custom API dependency resolver as shown in this gist:
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());
}
}
In your ~/App_Start/NinjectWebCommon.cs/CreateKernel
method that was created when you installed the NuGet add the following line after the RegisterServices(kernel);
line:
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
Configure your kernel:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFoo>().To<Foo>();
}
Hit F5 and navigate to /api/values
the bar
.Obviously when the RC hits RTM I hope there will be a Ninject.Mvc4
NuGet that will shorten those 10 steps to maximum 5.
Upvotes: 7