2014-12-12 14 views
30

Startup.cs là một cách mới để khởi chạy ứng dụng của bạn thay vì Application_Start trong Global.asax và nó ổn. Nhưng có một nơi để đặt logic teardown của tôi, ví dụ này:Có Application_End từ Global.asax trong Owin không?

public class WebApiApplication : System.Web.HttpApplication 
{ 
    protected void Application_End() 
    { 
    // Release you ServiceBroker listener 
    SqlDependency.Stop(connString); 
    } 
} 

Nhìn trong Microsoft.Owin namespace nhưng có vẻ như chỉ có OwinStartupAttribute. Điều này có nghĩa là các sự kiện vòng đời của ứng dụng vẫn được xử lý bởi cá thể System.Web.HttpApplication và không được đặc tả OWIN hỗ trợ?

Trả lời

36

AppProperties, được tìm thấy trong Microsoft.Owin.BuilderProperties, hiển thị CancellationToken cho OnAppDisposing.

Bạn có thể có được điều này thẻ và đăng ký một callback để nó

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     var properties = new AppProperties(app.Properties); 
     CancellationToken token = properties.OnAppDisposing; 
     if (token != CancellationToken.None) 
     { 
      token.Register(() => 
      { 
       // do stuff 
      }); 
     } 
    } 
} 
10

tôi đóng gói này lên trong một helper ít, do đó bạn có thể làm điều này:

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     app.OnDisposing(() => 
     { 
      // do stuff 
     }); 
    } 
} 

Các helper:

static class AppBuilderExtensions 
{ 
    public static void OnDisposing(this IAppBuilder app, Action cleanup) 
    { 
     var properties = new AppProperties(app.Properties); 
     var token = properties.OnAppDisposing; 
     if (token != CancellationToken.None) 
     { 
      token.Register(cleanup); 
     } 
    } 
} 
Các vấn đề liên quan