1

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();
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • 2
    `CA2000` is often wrong because C# doesn't provide a way to declare or specify object ownership transfer (unlike Rust), it also doesn't know about objects which implement `IDisposable` but should not normally be disposed or have special rules for disposing them (like `HttpClient`). – Dai Oct 26 '19 at 09:21
  • Please post your code. – Dai Oct 26 '19 at 09:23
  • @Dai yeah I know that, that's why I'm asking. Updated the code. – AgentFire Oct 26 '19 at 10:44

1 Answers1

1

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();
    });
}
Kahbazi
  • 14,331
  • 3
  • 45
  • 76