Jason Deacon | 14/09/2012
Often when developing a web application you will have static functional modules which may need to be swapped out or replaced based on external factors or processes. Some examples are static application-wide configuration classes, email sending providers, global helpers and HTTP harnesses.
Over the years I've honed in on a very straight forward approach to utilising IoC for static classes which turns out to be quite flexible.
It consists of three parts.
- The static access class
- The Interface
- The concrete implementations
The roles of which are defined:
1. The static access class: This is the class that the rest of the project uses. In this approach, it is a static class with static methods on it, typically one for each of the interface methods. The key concept of this approach is the static constructor, which is invoked automatically upon the first call into any of the static methods and sets a default instance to the private static interface field.
Example static access class:
2. The interface: This represents the methods that you will be replacing the functionality of. There is nothing special about this interface compared to any other interface.
The concrete implementations: These classes (one or many) implement the forementioned interface. Very straight forward, however there may be multiple concrete classes which could be used (set on the static access class) to provide a different set of functionality but still using the same functionality.
Example code of two concrete implementations:
The benefits of this approach come from the static access pattern and the ability to replace the implementations at runtime as needed based on configuration values, conditions, or anything really. This is useful for wrapping up various services which perform the same task (as in the email example above), wrapping up context-sensitive methods (acessing HttpContext.Current) which can be substituted for an implementation which doesn't use the context during testing (where a context is not available), and many more scenarios.
It's important to realise that this isn't a golden bullet, each scenario deserves to be evaluated and a solution decided upon without bias. Right tool for the right job, as they say.
Interested in learning more?
Wiliam is a leading supplier of web solutions and can provide expert advice to assist your business or organisation online.