Thursday, January 01, 2009

SelfHosting.cs

public class SelfHosting : IDisposable
{
private static ServiceHost serviceHost;
private ApplicationController controller;

///
/// Starts this instance. From Test Projects only.
///

public void Start()
{
Debug.WriteLine("Entering SelfHosting Start");
if (serviceHost != null)
throw new AddressAlreadyInUseException("Selfhosting already started");
serviceHost = new ServiceHost(typeof(OrderService));
serviceHost.Open();
ApplicationStart();
}

///
/// Stops this instance.
///

public void Stop()
{
Debug.WriteLine("Entering SelfHosting Stop");
if (serviceHost != null)
serviceHost.Close();
serviceHost = null;
}

private void ApplicationStart()
{
Debug.WriteLine("Entering SelfHosting ApplicationStart");
try
{
controller = new ApplicationController();
controller.Initialize(Environment.CurrentDirectory);
}
catch (ApplicationInitializationException exception)
{
LoggerFactory.New().Fatal(exception);
throw;
}
}



#region Implementation of IDisposable

private bool disposed;
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Implements to avoid when starting a
/// test after another one has failed leave a none clean state.
///

public void Dispose()
{
Debug.WriteLine("Entering SelfHosting Dispose");
if (!disposed)
{
Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}

///
/// Releases unmanaged and - optionally - managed resources
/// Set large fields to null
/// Free managed resources
///

/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
private void Dispose(bool disposing)
{
if (disposing)
{
controller.Dispose();
if (serviceHost != null)
serviceHost.Close();
serviceHost = null;
}
}

///
/// Releases unmanaged resources and performs other cleanup operations before the
/// is reclaimed by garbage collection.
///

~SelfHosting()
{
Dispose(false);
}

#endregion
}