Search code examples
c#.netasp.net-web-apiowinhttpconfiguration

Is it safe to dispose HttpConfiguration?


My CA2000 analyzer ("Dispose objects before losing scope") tells me to dispose of the HttpConfiguration instance once I've done customizing OWin's IAppBuilder.

I tried to do just that and everything works suspiciosly fine. MSDN doesn't tell anything about should I or should I not dispose HttpConfiguration, as it does about, say, Tasks ("dont bother disposing Task instances").

Since I don't want to leave an instance undisposed, as much as I don't want to find my web server crashed some day, what should I do?

Edit, part of my code:

public void Configuration(IAppBuilder appBuilder)
{
    EnableCookieAuth(appBuilder);
    UseWebApi(appBuilder);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Handled by ")]
private static void UseWebApi(IAppBuilder appBuilder)
{
    appBuilder.Use<ControlMiddleware>();

    using HttpConfiguration config = new HttpConfiguration();

    config.MapHttpAttributeRoutes();
    appBuilder.UseNinjectWebApi(config);
    config.EnsureInitialized();
}

Solution

  • The place that make sense to dispose httpConfiguration in owin app, is in OnAppDisposing

    HttpConfiguration httpConfiguration = new HttpConfiguration();
    app.UseWebApi(httpConfiguration);
    
    
    AppProperties properties = new AppProperties(app.Properties);
    CancellationToken token = properties.OnAppDisposing;
    if (token != CancellationToken.None)
    {
        token.Register(() =>
        {
            httpConfiguration.Dispose();
        });
    }