If you’ve used MVC, you know the System.Web.Abstractions API offers you a lot of capabilities to make it easy to write unit tests in your MVC controllers.  It’s really easy to setup a Moq or TypeMock unit test to create a fake implementation of objects like HttpContextBase.  Some objects are not as testable.  For instance, UrlHelper may not be as easy to implement testing with (although TypeMock can test pretty much any object very easily since it doesn’t require a DI setup or interfaces).  Rather than leverage this approach, I chose an approach not just limited to web forms, and something that may be available in a windows, silverlight, or WPF environment as well.  Welcome the ApplicationContext object and the IService interface.

ApplicationContext is a central object that is used to make services available to those who need it.  You have to go through a process of loading these services; however, this process isn’t that hard (will cover in another blog post).  To use the application context looks something like:

ApplicationContext context = ApplicationContext.GetCurrent();
ILoggerService service = context.GetService<ILoggerService>();

Every service that the application context uses implements IService (this interface doesn’t really do anything, but simply is used as a marker).  ILoggerService happens to be one of the services available (ILoggerService implements IService) and so it’s retrievable vai the ApplicationContext object.  Built into the framework is the NucleoContext namespace (which contains environment-agnostic services) and Nucleo.Web.Context (web/MVC specific services) that you can use the ApplicationContext object to retrieve.

The idea of this object is to make available core services.  For instance, in MVC, you can instantiate the service you need (HttpContextWrapper, HttpRequestWrapper, etc.).  Instead of using this, you can use the application context to request these services instead.  I don’t have all of the existing web services created; however, I do have services available for cookies, querystring, forms, and more.  Rather than create one big request object, I instead break up each of these into smaller services by function.

How do you retrieve?  That’s the purpose of the service loader, a subject we’ll discuss next.  You can get the latest code base for this example from: http://www.codeplex.com/nucleo