Something one should really strive for (in my opinion) is writing code in the spirit of the SOLID principles . One of the principles talks about DI( Dependency Injection) and even if it doesn’t refer strictly an Inversion of Control container – this is the easiest example of DI.
A simple example of DI would be an `OrderProcessor` class that needs to calculate on an order the tax that should be applied. That calculation would best be accomplished by a separate class, and because there might be more than one way to calculate taxes (different states from where the order is placed for example) `OrderProcessor` shouldn’t depend on a specific implementation of the tax calculator.
So an interface appears and instead of :
1: class OrderProcessor{
2: ITaxCalculator calculator1 = new SomeStateTaxCalculator();
3: ITaxCalculator calculator2 = new SomeOtherTaxCalculator();
4:
5: // do some logic and decide which calculator to use ..
6: }
you would have :
1: class OrderProcessor{
2: ITaxCalculator _calculator;
3:
4: public OrderProcessor(ITaxCalculator calculator){
5: _calculator = calculator;
6: }
7:
8: // now you have the calculator you need
9: // the responsibility of which calculator to use is no longer in this class.
10: }
To the PocketPC
And now after a short introduction to what Inversion of Control is about, I was surprised to find out that on the .Net Compact Framework is quite hard to find an IoC library.
Luckily, Germán Schuager, has put in the effort of creating a small version of an IoC container. That can be found at : http://code.google.com/p/compactcontainer/ . You’ll also find on that page a few links to short example of how to use the library.
For personal use I just made a small class to register types needed at startup, and be able to resolve dependencies at runtime.
1: static class IoC
2: {
3: private static CompactContainer _container;
4: private static bool _configured;
5: public static void Configure()
6: {
7: _container = new CompactContainer { DefaultLifestyle = LifestyleType.Transient };
8:
9: _container.AddComponent(typeof(ISettingsManager), typeof(SettingsManager), LifestyleType.Singleton);
10: _container.AddComponent(typeof(IRatesDownloader), typeof(RatesDownloader));
11: _container.AddComponent(typeof(IRatesParser), typeof(RatesParser));
12: _container.AddComponent(typeof(IWebUpdater), typeof(WebUpdater));
13: _container.AddComponent(typeof(IContextPersister), typeof(ContextPersister));
14:
15: _configured = true;
16: }
17:
18: public static T Resolve<T>()
19: {
20: if (!_configured)
21: throw new Exception("The IoC container was not configured before use. Call Configure() on the IoC class before the Application.Run");
22: return _container.Resolve<T>();
23: }
24: }