Search code examples
c#asp.net-web-apidependency-injectionowincastle-windsor

When using an OWIN startup class, how do I dispose of my Castle Windsor container after registering my dependencies?


I was having issues whereby my container was not being called in when registered in my global.asax, so I thought that this could be because I am now using an OWIN startup class. I've moved the instantiation of the container to this class now. I'm wondering whether this is appropriate to do:

[assembly: OwinStartup(typeof(Startup))]
namespace Namespace.WebApi

public class Startup : IDisposable 
{
    private readonly WindsorContainer _Container;
    public Startup()
    {
        _Container = new WindsorContainer();
        _Container.Install(FromAssembly.Named("Namespace.WebApi.Installers"));
    }

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.Services.Replace(typeof(IHttpControllerActivator),
            new WindsorHttpControllerActivator(_Container));
        /// other configuration
    }

    public void Dispose()
    {
        _Container.Dispose();
    }
}

Solution

  • You can include the Owino NuGet package and use the RegisterForDisposal extension like this:

    public void Configuration(IAppBuilder app)
    {
        /// (...)
    
        app.RegisterForDisposal(_Container);
    }
    

    or you can look at how the method is implemented and make your own implementation.