Mini IOC and Static gateway logging

DI (IOC) containers are a powerful tools, the reasons why you would and would not use one I will leave to your better judgement. Which one you would use I will also leave to your judgement, however if you need a light weight, build in IOC then one of the best examples I have seen (and used) is Ken's 33 line Mini IOC. It is simple to use and simple to implement

   1:  IOC.Register<IShipping, MyShipping>();        
   2:  IOC.Register<IBasket, MyBasket>();        
   3:  IOC.Register<IView, MyView>();
   4:  var bank = IOC.Resolve<IPresenter>();

logging is a little tricky, to the rescue comes JB's static gateway logging example. This is a neat solution to the problem as we now use IOC to resolve a logging class dependency, so first we need to create a dependency class for our mini IOC.

   1:      public class IOCResolver : IDependencyResolver
   2:      {
   3:          public Interface GetImplementationOf<Interface>()
   4:          {
   5:              return IOC.Resolve<Interface>();
   6:          }
   7:      }

Next we need a logging class Factory

   1:      public class DebugLogFactory : ILogFactory
   2:      {
   3:          public ILog CreateFor(Type type)
   4:          {
   5:              return new DebugLogger();
   6:          }
   7:      }

and the logging class 

   1:       public class DebugLogger : ILog
   2:          {
   3:              public void Debug(string message)
   4:              {
   5:                 System.Diagnostics.Debug.WriteLine("DEBUG: " + message);
   6:              }
   7:   
   8:              public void Warning(string message)
   9:              {
  10:                  System.Diagnostics.Debug.WriteLine("WARNING: " + message);
  11:              }
  12:   
  13:              public void Fail(string message)
  14:              {
  15:                  System.Diagnostics.Debug.WriteLine("FAIL: " + message);
  16:              }
  17:          }
  18:      }

Now we have our various parts we first set up the Resolver which then goes looking in the IOC for our logging Factory (thus we also need to add our logging Factory to the IOC), all in all we end up with

   1:  DependencyResolver.InitializeWith(new IOCResolver());
   2:  IOC.Register<ILogFactory, DebugLogFactory>();
   3:  IOC.Register<IShipping, MyShipping>();        
   4:  IOC.Register<IBasket, MyBasket>();        
   5:  IOC.Register<IView, MyView>();
   6:  var bank = IOC.Resolve<IPresenter>();

now we can log simply by using

   1:  Log.For(this).Debug("testing")

No Comments