Thursday, February 23, 2012

Use Windsor as Dependency Resolver for Asp.Net Web Api

Here is a little code snippet you can use to integrate Windsor into Web Api. One important note about this class is that we are only resolving Type we care to register to our container and we leave to rest to Web Api internal dependency resolver. We do that by return null in the GetService method and returning an empty collection for GetServices method. You should read Using the Web API Dependency Resolver by Mike Wasson to have a better understanding of how the process work.

public class WindsorDependencyResolver : IDependencyResolver
{
  private readonly IWindsorContainer _container;

  public WindsorDependencyResolver(IWindsorContainer container)
  {
    _container = container;
  }

  public object GetService(Type serviceType)
  {
    return _container.Kernel.HasComponent(serviceType) ?
      _container.Resolve(serviceType) : null;
  }

  public IEnumerable<object> GetServices(Type serviceType)
  {
    return _container.Kernel.HasComponent(serviceType) ?
      _container.ResolveAll(serviceType).Cast<object> () : new List<object>();
  }
}

The next step is to register your Dependency Resolver. I added this line to my Application_Start.

GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new WindsorDependencyResolver(IocContainer));

No comments: