In self-hosted OWIN Web API, how to run code at shutdown?

后端 未结 2 1596
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 01:29

I am self-hosting a OWIN Web API using these code snippets:

class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config =          


        
相关标签:
2条回答
  • This can be achieved by getting the host's cancelation token and registering a callback with it like so

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

    I was told by someone on the Katana team that this key is for host specific functionality and therefore may not exist on all hosts. Microsoft.Owin.Host.SystemWeb does implement this, but I'm not sure about the others.

    The easiest way to verify if this will work for you is to check app.Properties for the host.OnAppDisposing key.

    0 讨论(0)
  • I think there is a better way to get the CancellationToken:

    var properties = new AppProperties(app.Properties);
    CancellationToken token = properties.OnAppDisposing;
    

    AppProperties is under namespace Microsoft.Owin.BuilderProperties, which comes from this nuget package: http://www.nuget.org/packages/Microsoft.Owin/

    The description of property OnAppDisposing says:

    Gets or sets the cancellation token for “host.OnAppDisposing”.

    Please refer to: http://msdn.microsoft.com/en-us/library/microsoft.owin.builderproperties.appproperties%28v=vs.113%29.aspx

    0 讨论(0)
提交回复
热议问题