Skip to content

Instantly share code, notes, and snippets.

@htuomola
Forked from haacked/ServiceResolverAdapter.cs
Created August 29, 2012 18:09
Show Gist options
  • Save htuomola/3516391 to your computer and use it in GitHub Desktop.
Save htuomola/3516391 to your computer and use it in GitHub Desktop.
ServiceResolverAdapter: Allows you to use the ASP.NET MVC DependencyResolver for ASP.NET Web API
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
public class ServiceResolverAdapter : IDependencyResolver
{
private readonly System.Web.Mvc.IDependencyResolver dependencyResolver;
public ServiceResolverAdapter(System.Web.Mvc.IDependencyResolver dependencyResolver)
{
if (dependencyResolver == null) throw new ArgumentNullException("dependencyResolver");
this.dependencyResolver = dependencyResolver;
}
public object GetService(Type serviceType)
{
return dependencyResolver.GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return dependencyResolver.GetServices(serviceType);
}
public IDependencyScope BeginScope()
{
// This doesn't support child scopes, so we simply return 'this'.
return this;
}
public void Dispose()
{
// When BeginScope returns 'this', the Dispose method must be a no-op.
}
}
public static class ServiceResolverExtensions
{
public static IDependencyResolver ToServiceResolver(this System.Web.Mvc.IDependencyResolver dependencyResolver)
{
return new ServiceResolverAdapter(dependencyResolver);
}
}
@htuomola
Copy link
Author

Small changes to make it work with MVC 4 final (RTW). Also added namespaces for clarity.

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