Configuring dependency injection

Dependency injection in ASP.NET MVC controllers

The ServiceLocator is a very powerful dependency injection class. To allow the ASP.NET MVC to use the ServiceLocator as dependency resolver, simply call the following in the global.asax class:

Catel.Mvc.DependencyInjectionConfig.RegisterServiceLocatorAsDependencyResolver();

Dependency injection in ASP.NET Web api controllers

If you are using web api as well, a few more things must be done.

1. Create new type implementing the IDependencyResolver of the web api:

public class CatelWebApiDependencyResolver : Catel.IoC.DependencyResolver, System.Web.Http.Dependencies.IDependencyResolver
{
	private readonly IServiceLocator _serviceLocator;
	private readonly ITypeFactory _typeFactory;

	public CatelWebApiDependencyResolver()
	    : this(ServiceLocator.Default) { }
		
	public CatelWebApiDependencyResolver(IServiceLocator serviceLocator)
	{
	    Argument.IsNotNull(() => serviceLocator);
		
		_serviceLocator = serviceLocator;
		_typeFactory = serviceLocator.ResolveType<ITypeFactory>();
	}
	
	public System.Web.Http.Dependencies.IDependencyScope BeginScope()
	{
		// This resolver does not support child scopes, so we simply return 'this'.
		return this;
	}
 
	public void Dispose()
	{
		// nothing to dispose
	}
}

2. Register the class manually:

GlobalConfiguration.Configuration.DependencyResolver = new CatelWebApiDependencyResolver();