When programming with ArcObjects and ArcGIS Server, code often follows a common pattern of connecting to ArcGIS Server, getting hold of an IServerContext, doing some work, and releasing the context. This leads to a lot of unnecessarily repeated setup and teardown code, usually taking a form similar to the following example:
IServerContext context = null;
try
{
IGISServerConnection conn = new GISServerConnectionClass()
as IGISServerConnection;
// Connect as ASPNET or NETWORK SERVICE.
// Get optional host setting from web.config,
// or use localhost if not found.
string host = ConfigurationManager.AppSettings["AGSHost"];
if (String.IsNullOrEmpty(host))
{
host = "localhost";
}
// Make connection
conn.Connect(host);
IServerObjectManager som = conn.ServerObjectManager;
context = som.CreateServerContext("MyServer", "MapServer");
// Do some stuff with the server context
}
finally
{
if (context != null)
{
context.ReleaseContext();
}
}
In this example, there is a lot of boilerplate happening just to get to the server context and do something interesting. Seeing this kind of code repeated throughout an ArcGIS Server project made me a little queasy as it violates the DRY Principle, so that got me thinking about how to eliminate it. More...