Question

I have tried to implement Castle Windsor into my ASP.NET Web API project by following the guide by Mark Seemann. But when I try to run the code it gives me a ComponentNotFoundException exception. I mean that I should have registered the dependency right.

I really hope that someone has a solution to my problem. I have tried to search for a solution but with out any luck.

Global.asax

public class WebApiApplication : System.Web.HttpApplication
{

    private readonly IWindsorContainer _container;

    public WebApiApplication()
    {
        _container = new WindsorContainer().Install(new ControllerInstaller());
    }

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(_container));
    }

    public override void Dispose()
    {
        _container.Dispose();
        base.Dispose();
    }
}

IHttpControllerActivator implementation

public class WindsorCompositionRoot : IHttpControllerActivator
{
    private readonly IWindsorContainer _container;

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

    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        var controller =
            (IHttpController)_container.Resolve(controllerType);

        request.RegisterForDispose(
            new Release(
                () => _container.Release(controller)));

        return controller;
    }

    private class Release : IDisposable
    {
        private readonly Action release;

        public Release(Action release)
        {
            this.release = release;
        }

        public void Dispose()
        {
            release();
        }
    }
}

ControllerInstaller

public class ControllerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<IGymnastDataAccess>().ImplementedBy<GymnastDataAccess>());
    }
}

Controller

public class GymnastController : ApiController
{
    private readonly IGymnastDataAccess _gymnastDataAccess;

    public GymnastController(IGymnastDataAccess gymnastDataAccess)
    {
        _gymnastDataAccess = gymnastDataAccess;
    }

    public IEnumerable<string> Get()
    {
        _gymnastDataAccess.Load();

        return new string[] { "value1", "value2" };
    }
}
Was it helpful?

Solution

Castle Windsor do not support automatic resolve of concrete classes out of the box, so you should register your controller class in container:

container.Register(Component.For<GymnastController>());

or implement ILazyComponentLoader like here to get automatic resolve of concrete classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top