0

I have a .NET C# WebAPI program and I'm using an external library I need to dispose just before the main application quits.

That's my startup function:

public class Startup
{
        private static void WebApiSetup(IAppBuilder app)
        {
            using (var configuration = new HttpConfiguration())
            {
                app.UseWebApi(configuration);
            }
        }
}

The external library is a static class so I just have to call MyLib.DeInit();. Unfortunately I don't see any suitable place to call that function, there's no "here we quit" function to customize. Someone is talking about registering a callback to a "cancellation token" but I don't know how to do it

Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

1 Answers1

1

You can run code on 'shutdown' like this:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var context = new OwinContext(app.Properties);
        var token = context.Get<CancellationToken>("host.OnAppDisposing");
        if (token != CancellationToken.None)
        {
            token.Register(() =>
            {
                // code to run at shutdown
            });
        }
    }
}

Properties are part of the base Owin Interface for IAppBuilder:

// Decompiled with JetBrains decompiler
// Type: Owin.IAppBuilder
// Assembly: Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5
// MVID: C152461C-65C1-4F51-912C-2454A21D9BAD
// Assembly location: E:\Felinesoft\BACP\DEV\WEB\BACP.Web-AzureSearch\BACP.Web.Presentation\Bin\Owin.dll

using System;
using System.Collections.Generic;

namespace Owin
{
  public interface IAppBuilder
  {
    IDictionary<string, object> Properties { get; }

    IAppBuilder Use(object middleware, params object[] args);

    object Build(Type returnType);

    IAppBuilder New();
  }
}
Jason H
  • 4,996
  • 6
  • 27
  • 49