While I’ve been using Castle’s Windsor for a bit now, but wanted to get some StructureMap code running just to get some exposure to it; I’ve heard good things. I decided to set a simple goal and try to achieve it using StructureMap. Here’s my goal:
1. Request a concrete type of an interface and run a method.
2. Change the implementation of the interface (during runtime) and run the same method to compare against the original.
3. Toggle back to the originally configured class.
I assumed that building a small “one-off” project that could do this would give me a good start to understanding the StructureMap syntax. The idea stemmed from thoughts of logging certain data using an administrative login. By swapping out the runtime type without rebuilding the application, you can apply different logic (via a Decorator Patttern) to track timings and any other data available to you.
My example is quite boring and unfortunately not useful or real-world, but it gets the job done to give me a base to get something like this set-up. I have my Interface and Classes code as the following:
You’ll see the only difference is the output of the Print() function. Now swapping between the two, I’d expect different results, all during runtime, during my main method, as follows:
This requests the concrete implementation of my interface and executes the method. The following step is to change to another type that implements the interface, thus agreeing to the contract and running the same method. Obviously it implements it differently, only for visualization purposes, then toggle back to the original.
During this “swapping” all I’m doing is requesting another instance of the Runner class. The Runner class has a constructor dependency on IPrinter, which is “injected” during creation. This is how it gets the new version of the IPrinter object, which is now different, via StructurMap’s Inversion of Control; thus creating the differing output when asked to run the Print() method.
For anybody familiar with IoC and DI this might seem “old-hat”, but I thought this small sample forcing myself to use and IoC that I’m not familiar with, that would give me a decent base to look into using it for another project. So far I really like the syntax, it seems a lot more natural to me.
Post Footer automatically generated by Add Post Footer Plugin for wordpress.