Created
January 7, 2016 09:49
-
-
Save dealproc/2eb62c238688b169d848 to your computer and use it in GitHub Desktop.
Azure Worker Role for hosting an Owin application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Your.Product.Namespace | |
{ | |
public class WorkerRole : RoleEntryPoint, IDisposable | |
{ | |
readonly TaskCompletionSource<bool> _endRole = new TaskCompletionSource<bool>(); | |
readonly ManualResetEvent _runCompleteEvent = new ManualResetEvent(false); | |
IDisposable _app; | |
bool _disposed = false; | |
~WorkerRole() | |
{ | |
Dispose(false); | |
} | |
public override void Run() | |
{ | |
var httpEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Http"]; | |
var httpsEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Https"]; | |
var httpUri = string.Format("{0}://{1}", httpEndpoint.Protocol, httpEndpoint.IPEndpoint); | |
var httpsUri = string.Format("{0}://{1}", httpsEndpoint.Protocol, httpsEndpoint.IPEndpoint); | |
var options = new StartOptions(); | |
options.Urls.Add(httpUri); | |
options.Urls.Add(httpsUri); | |
try | |
{ | |
_app = WebApp.Start<Startup>(options); | |
_endRole.Task.Wait(); | |
} | |
catch (Exception ex) | |
{ | |
... do whatever logging you need. | |
throw; | |
} | |
finally | |
{ | |
_runCompleteEvent.Set(); | |
} | |
} | |
public override void OnStop() | |
{ | |
_endRole.SetResult(true); | |
_runCompleteEvent.WaitOne(); | |
_app.Dispose(); | |
base.OnStop(); | |
} | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (!disposing || _disposed) { return; } | |
if (_runCompleteEvent != null) | |
{ | |
_runCompleteEvent.Dispose(); | |
} | |
if (_app != null) | |
{ | |
_app.Dispose(); | |
_app = null; | |
} | |
_disposed = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment