I want to implement Dependency Injection in WebApi application using Castle Windsor. I have following sample code –
Interface –
public interface IWatch
{
{
DateTime GetTime();
}
}
Following Watch class implements IWatch Interface –
public class Watch:IWatch
{
public DateTime GetTime()
{
return DateTime.Now;
}
}
WebApi Controller – WatchController as below –
public class WatchController : ApiController
{
private readonly IWatch _watch;
public WatchController()
{
_watch = new Watch();
}
//http://localhost:48036/api/Watch
public string Get()
{
var message = string.Format("The current time on the server is: {0}", _watch.GetTime());
return message;
}
}
Currently I am initiating IWatch object with Watch in WatchController constructor. I want to remove dependency of initializing IWatch inside constructor using Windsor Castle dependency injection principle.
Can anybody provide me the steps to implement dependency injection in this case of WebApi? Thanks in advance!
Best Answer
CodeCaster, Noctis and Cristiano thank you for all your help and guidance.. I just got the solution for my above query -
The first step is to use nuget to install the Windsor.Castle packages in the WebApi solution.
Consider the following code snippet -
Interface IWatch.cs
Class Watch.cs
The ApiController WatchController.cs is defined as follows: -
In the controller we have injected the dependency through IWatch object in the WatchController constructor. I have used IDependencyResolver and IDependencyScope to achieve dependency injection in web api. The IDependencyResolver interface is used to resolve everything outside a request scope.
WindsorDependencyResolver.cs
WindsorDependencyScope.cs
WatchInstaller.cs
Installers are simply types that implement the IWindsorInstaller interface. The interface has a single method called Install. The method gets an instance of the container, which it can then register components with using fluent registration API:
Finally, we need to replace the default dependency resolver with the Windsor implementation in Global.asax.cs (Application_Start method) and install our dependencies: