如何在.NET C#WebAPI程序上取消初始化库

时间:2017-05-22 14:22:11

标签: c# .net asp.net-web-api

我有一个.NET C#WebAPI程序,我使用的是在主应用程序退出之前需要处理的外部库。

这是我的startup功能:

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

外部库是一个静态类,所以我只需要调用MyLib.DeInit();。不幸的是,我没有看到任何合适的地方来称呼这个功能,没有"在这里我们退出"功能定制。有人在谈论注册一个"取消令牌"但我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

您可以在'关闭'上运行代码像这样:

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
            });
        }
    }
}

属性是IAppBuilder的基础Owin接口的一部分:

// 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();
  }
}