Inversion of Control, Dependency Injection and Service Locators oh my!

This post is part of my “Software Development” series. The TOC for the entire series can be found here.



In this post, we’re going to look, at a higher level, at the reasons for and benefits of using a framework for Inversion of Control (IoC), Dependency Injection (DI) and Service Location. I’m not going to spend a large amount of time in this blog series describing the intimate details of what IoC, DI and Service Locators are.  Martin Fowler did a fantastic job of it and there’s no point in me just regurgitating his work.


Instead, I’ll give my vision of what they are and how they are relevant to how I architect and develop solutions.  It’s important to note that I’m starting out this series with high-level thoughts about architecture and design.  I’m not just laying down some code, leaving the decisions about how things will interact to some arbitrary, organic process.  This is how software development gets done. 


You’ve got to think about not just the next step, but visualize the end point several months, or even years out and try to connect the dots back to where you are today.  If I implement something in a certain way today, is it going to screw me 3 months down the road?  Spending an extra day now thinking about architecture is going to turn into saving weeks of the customer breathing down your neck and you pull out your hair and work late night trying to hammer a square peg into a round hole.


So let’s look at IoC, DI and Service Location and how they’re going to help us build better software.  Inversion of Control as a concept is something that’s really broad.  It’s really anything that turns the older procedural way of developing upside down (i.e. inverts program control, hence the name).  Moving from a console app to a windowed, event-driven app is technically inversion of control, so you’ve already been using IoC. 


To talk about IoC as a useful concept that’s actually going to be of use, we’ll be using some smaller units/principals of IoC.  The two we’re going to look at are Dependency Injection, or DI, and Service Location.  Neither one is complex or arcane, and you probably already use them to some degree.


Let’s assume we have two arbitrary classes, A and B, and that A uses an instance of B internally.  There are, essentially, 3 ways that A can get the instance of B. 


First, it can directly create it by calling new B().  While this is simple, it’s the least preferred, and generally worst, way to do it.  By directly creating B, A is now tightly coupled to B’s implementation.  B can’t be easily changed out to something else.  If B is in another assembly, A has to have a reference to it.  It’s also difficult to test A by itself. 


The second way that A can get B is that whoever created the instance of A could pass into it an instance of B.  Maybe through a constructor

var b = new B();
var a = new A(b);

or through a property

var b = new B();
var a = new A();
a.B = b;

This is called Dependency Injection. The former is constructor injection, the latter is property injection – not so complex, eh?  This is useful because, if B is an interface, it’s really easy to swap out the implementation passed to A and the assembly containing A doesn’t necessarily have to have a reference to the assembly holding the implementation of B – it only needs a reference to the interface.  This is really nice when we want to do mocking.


The third way that A can get B is to go get it from some central repository or “factory”.

B B { get; set; }

public A()
{
this.B = MyClassFactory.GetB();
}


This is service location.  A doesn’t really know what B is, it lets the service locator (MyClassFactory) resolve that.  This is really helpful for plug-in architectures as well as for lazy loading objects.


Generally speaking, your code should only be doing #2 (DI) and #3 (service location) for objects of any complexity.  This is not to say that you shouldn’t ever call the new operator in your code.  There’s obviously a grey line out there below which it would be pretty stupid to not just use new for.  If you need to use a simple entity class or structure, then creating one makes sense.  If you need access to the DAL and I see you creating a DAL object in your View, you’re fired.


There are plenty of framework out there that provide DI and service location –  Ninject, Unity, CastleWindsor, StructureMap, Autofac – the list goes on and on.  Instead of using one of them, however, I chose to roll my own.  Normally I wouldn’t recommend such a drastic action – after all reinventing the wheel isn’t usually wise – but in my case it was essentially required, so I’ll give you the short back story.


My team and I had been working on a large desktop application.  We had designed it from the start using Microsoft’s SCSF/CAB framework, which provide DI, service location and a load of other stuff.  It turned out that we were using maybe 10% of the framework, and that the framework’s Studio plug-ins were causing fits with some installations of Studio.  Spending time screwing with Studio plug-ins and trying to get things to compile is a terrible waste of manpower, so we were already getting close to jettisoning it when we decided that we wanted the core of our app logic to be Compact Framework compatible.


Well Microsoft’s “port” of the SCSF to the Compact Framework, called the MCSF, turns out to be a bloated, unbelievably slow, steaming pile of dog crap.  Side note: just because something compiles under the Compact Framework does not mean it should be used in the Compact Framework.  Well, I didn’t want to refactor everything we’d done to some other IoC framework, plus I couldn’t find one at the time that actually worked for the Compact Framework, so I decided to create one. 


I took the tack that I’d create it for the CF first, with a high emphasis on small footprint, minimal resource usage and speed and I simply matched the SCSF object model where our code base interfaced with it and where it made sense – in some places I didn’t like how the SCSF had done things, so I “fixed” their mistakes.  The end result was the OpenNETCF.IoC framework, which turns out to stack up quite well against the other frameworks.  It also has the huge benefit of working on the Full Framework, Windows Phone 7 and MonoTouch (probably MonoDroid as well, though I’ve not tested that). We’ll be looking at OpenNETCF.IoC in a lot more depth in this series.

On Software Development

This post is part of my “Software Development” series.  The TOC for the entire series can be found here.






Developing good software is hard.  Really hard.  Sure, anyone can buy a book on writing software or pull up some code samples and get something that compiles and runs, but that’s not’s really developing software.  A lot of code in the wild – I’d bet a vast majority of it – just plain sucks.


It’s hard to point out where the blame lies.  It seems that most developers are environmentally or institutionally destined to write bad code. Schools teach how to write code, but not how to architect it or to follow reasonable design practices.  In the zeal for clarity, publishers churn out books, blogs and samples that show bad practices (when is it ever a good idea to access a data model from your UI event handler?).  Managers and customers alike push hard to get things done now, not necessarily done right – only to find months or years later that doing it right would have saved a boatload of time and money.  And let’s face it – many developers are simply showing up to work to pull a paycheck.  You know who they are.  You’ve no doubt worked with them in the past.  You’re probably working with them now.


I was watching Gordon Ramsay the other day and it occurred to me that he and I are alike in our own peculiar way.  I’m not saying that I see myself as the “Gordon Ramsay of Software Development” – hardly –   but we share a common trait.  Just as Gordon gets angry and starts spewing colorful language when he walks into a crap kitchen, it bothers the hell out of me to see complete idiots in my chosen field out there just making a mess of things.  When I see bad code – not necessarily minor errors, or code that could be refactored and made better – but just outright shit code that should not have occurred to a developer in the first place it pisses me off.  By the nature of my work, often getting called in only when the project is off the rails, I see it all the time. Code that, on review, a peer or mentor should have seen and said “Whoa!  There’s no way that’s going into our code base”.  Code that just makes it harder for the next person to do their job.


In an effort to simplify things for my own code, for my customers’ code as well as anyone who is willing to listen to my ravings, I’ve spent a lot of time building, testing, fixing and extending tools and frameworks that many of which I turn around and give away.  This isn’t out of altruism, no, it’s largely because I’m a lazy developer.  I hate writing the same thing twice.  When I start a project, I don’t want to spend large amounts of time building up the same infrastructure that every project needs. Building up a framework for handling UI navigation isn’t what I’d call interesting, but just about every project needs it.  Handling object dependencies and events is common.  Writing a DAL for serializing and deserializing entities is not just drudgery, I find it’s highly susceptible to errors because you end up doing a lot of copy and paste.


I have these cool tools and frameworks that I use in literally every project I work on now.  That’s great for me, but it doesn’t really help others, right?  Without reasonable documentation or explanation, only a small handful of people are going to go through the effort of getting the tools and trying to understand them – even if they are deceptively simple and could potentially save you weeks of effort. 


So I’ve decided to put together a series of blogs over the coming weeks and months that explain, hopefully in simple terms, what these frameworks do, how to use them, and most importantly, why they are worth using.  There’s nothing groundbreaking here.  I didn’t invent some new way to do things.  I’ve simply appropriated other peoples’ ideas and extended them to work in the environments that I work.


Generally I’ll be covering the following topics and frameworks:



  • Dependency Injection and Inversion of Control (using OpenNETCF IoC)
  • Event Aggregation (using OpenNETCF IoC)
  • Plug-in Architectures and interface-based programming (using OpenNETCF IoC)
  • Software features as services (using OpenNETCF IoC)
  • Data Access through an ORM (using OpenNETCF ORM)
  • Parameter Checking (using OpenNETCF Extensions)
  • Exposing data services over HTTP (using Padarn)
  • Whatever else I think of

If there’s a topic you’d like me to talk about, feel free to send me an email.  I may turn on comments here and let you post ideas, but I find that when I enable comments on my blog, I start getting more comment spam than I really want to deal with, so if comments are turned off just drop me a line.

OpenNETCF.IoC: New Release

We’ve been heavily dogfooding the IoC project (and others) lately and I finally took the time today to back-port the fixes and updates to the public code. This is being used for a solution that runs on both the desktop and the compact framework, so it’s been heavily tested under both of those environments. The new release (1.0.11235) is now available on Codeplex.

Benchmarking OpenNETCF’s IoC Framework

Last night I was browsing around the Net on a back tracking a visit to the OpenNETCF Inversion Of Control (IoC) project.  I came upon a page where someone had done a quick set of benchmarks for many of the popular IoC engines out there [http://www.iocbattle.com/].  This got me wondering.  How would OpenNETCF IoC stack up against these, after all I’ve never done any performance comparisons against any other framework.


Well I downloaded the benchmarking code the original author had put together and added added an IoC version of the test (which was really easy to do).  I then ran the singleton test, which essentially registers a set of dependent classes by interface name (in theRootWorkItem.Services collection) and then uses the IoC engine to extract the from the store 1,000,000 times.  It then reports how long it took to do the extraction.  Simple enough.


Here are the results:



The hard numbers are not really important – the actual number is going to depend on your hardware – what is interesting is how they look relative to one anotehr.  You can see that if you exclude the new operator (which isn’t IoC, it’s just there for reference), then the Dynamo engine (which is the test author’s engine) preforms the best.  Now I know nothing about that engine, so if you’re interested, I’ll let you investigate that further.


What was interesting to me is that IoC is three times faster than the next fastest IoC engine (AutoFac), five times faster than Structure Map, roughly 6 times faster than Castle Windsor or Unity and a whopping 25 times faster than the ever-popular Ninject engine.  Evidently my focus on performance when developign the engine paid off.


How about the time it takes to register all of the types that get created?  Are we paying the piper at creation time in order to save it at resolution?  Here are the time results for setup (instantiation of singletons):



Again, IoC is at near front of the pack.


Binary size isn’t overly relevent any longer, I mean if you’re using managed code then you’ve already made the decision that file sizes aren’t critical, but it’s still interesting to look at.  Here’s a breakdown of the sizes of each of the libraries.  The libraries marked with an asterisk also have configuration files that are *not* included in the resported size (so deployment would actually be larger than what the graph shows).



All in all, I’m pretty pleased with the results.  We dogfood the OpenNETCF IoC framework for all of our projects, both desktop and Compact Framework, so it gets a fair amound of testing and beating and you can be assured that if there are bugs I’ll do my best to resolve them.  If you’ve not taken a look at the project, give it a try.


 

Improving CF App Aesthetics

One complaint I see a lot about apps built using the Compact Framework is that they look terrible.  It doesn’t have to be that way, and honestly the Compact Framework really isn’t at fault here.  Generally speaking the problem is that developers are lazy and want to just use what’s in the off-the-shelf toolbox.  If you do that, then yes, you’ll have something that looks like a Windows 95 application.  But again, I don’t fault the CF for that, I fault developers (or more likely their managers).


If you want an app to have good aesthetics you need two things:



  1. To hire a real graphic designer to at least produce collaterals
    At the risk of making broad generalizations, I’ll state that developers suck at producing graphics (it’s OK, graphic designers suck at writing code).  You wouldn’t hire a plumber to hang drywall, why on earth are you having developers create UI?  Hire a designer that has experience building UI collaterals and you’ll find that not only will your app look a thousand times better, it will get done faster than having your devs hack at it.
  2. To break your developer’s reliance on the off-the-shelf controls
    Using the controls that install with the CF is a sure-fire way to end up with a dated-looking app.  This doesn’t mean you have to go buy a 3rd-party set of controls; that may help, but don’t just assume it’s going to solve the issue.  What we’ve done internally is to build a set of controls that we use.  Most people would be surprised to know that we have a very small set. We wrote the entire device application for a commercially-available time clock that you’d never know was based on CE by looking at it and I believe that the number of Control types used (other than a Form and SmartPart) was one.  That’s right – we used a single control type for everything.  We use it as a Button, a Label, a CheckBox and stacked together to make a List (it’s a touch device with only 5 or 6 items visible at a time).

There’s not much I can do for you on point #1, but for #2 I can at least give you the control we use.  It’s called ImageButton due to it’s genesis as a button that, surprisingly, held an image.  It got more complex as we needed and added new capabilities and features.  You can set the up and down images (to get that nice “inverted” look on click), put align text left, center or right (with an appropriate margin if you’d like), put text and images together, and several other features.


Here are some quick screen shots:



The first screen shows rounded buttons (the change to a blue background when clicked) with the grey “>” and the text aligned in different ways.  Note that the right and left justified text have a fairly large margin; this is settable.


The second is probably not the greatest picture as it looks a lot like a normal checkbox, but those checkboxes are actually images.  You could easily change them to a round “bubble” or a box with a check that extends beyond the box border.


The third is a simple drawn-gradient background.  Note that the button in the upper middle (which again is an ImageButton) has rounded corners and the gradient background is visible through the transparent corners of the button (this was a real challenge in the CF).  The “State1” text on this view is actually another ImageButton control so it can respond to clicks.  Again note that the gradient background is visible through the control.


The final view shows yet another use of the control.  The two-state capability is actually done with two images. The control is a single ImageButton and when it gets clicked, we swap the image to toggle the “on” or “off” selection. Notice that the text in the images is less pixelated becasue we don’t have ClearType turned on.


Since I didn’t really have a better place to put the code, and since the sample app showing it was using the IoC framework, I’ve simply put the code in the OpenNETCF IoC Framework tree on Codeplex (under Samples). Also note that the code for this is not yet in the release. That means you need to pull it from the source view (starting with change set 59250)

Updates to ORM and IoC projects

We’ve shipped a first version of a customer project.  That’s always good news, but the benefit to the community at large is that updates, improvements and fixes to both the ORM and IoC projects from that project have now propagated to the public code bases.


The IoC changes are pretty minor, which tells me that it’s a pretty robust and mature library on the whole.


ORM had a load of changes in the SQL Compact implementation.  The interface for the DataStore has expanded by several methods due to use-cases I needed methods for and it’s got a whole lot of performance improvements added.  ORM and is now shipping to real-world customers in a handheld product, so I consider it “release” quality.


Be aware that neither project has these changes rolled into a release package yet, so if you want these changes, grab the latest change set from the “Source Code” tab on the appropriate project page.

OpenNETCF IoC: Now supporting WinPhone!

Today I decided to finally get around to testing out the IoC core library on Windows Phone 7.  Of course I couldn’t be lucky enough for it to just compile out of the box and work. The usage of the Control class for marshaling events made it a little bit challenging, but it really didn’t require a whole lot of code changes to get the code base to continue to work for the Desktop, the Compact Framework and Windows Phone.  The latest release now has a solution and a Silverlight project for WinPhone.


Why would you want to use this IoC container?  Well I use it becasue it’s lightweight and because I can use the same framework everywhere.  I don’t have to learn a new framework when I’m using the desktop, the CF and now the phone.  It keeps my life simpler and allows better code reuse for me.

OpenNETCF.IoC : Location Module

Since I use the OpenNETCF.IoC framework in just about every project I do any more, you can imagine I’ve created a pretty good collection of Modules and Services for common business problems I run into.  I’ve decided that I’m going to start putting some of these out in the public domain along with the framework and my first release is the OpenNETCF.Location module.  It’s basically a module that prvides a GPS location service (GpsService to be exact). 


The default implementation is wrapper around the GPS intermediate driver, but it’s not using the CF classes that Microsoft ships with the WinMo SDKs.  I looked at Microsoft’s implementation and it felt really ugly to me, so I rewrote it the way it should have been done in the first place.  I don’t yet have a simple sample application extracted for it (I have apps that use it, but they’re too complex for a sample), but I’ll add one as time permits.


The code is part of the latest change set (49823) – it’s not yet in the release download – so if you want it, get it off of the Source Code page.

Connecting to TFS 2010 from Studio 2008

Codeplex recently updated the server hosting the IoC project to TFS10.  Since we still have to use Studio 2008 for device development, I had to do some client changes for bindings to get to the server.  TFS 2010 added the concept of a “Team Project Collection”, which Codeplex is using – but Studio 2008’s Team Explorer dialog has no provision for it.  It took me a while with a search engine to figure out how to actually attach – basically you have to manually type the full path into the connection dialog in Team Explorer like so:


http://<serverName&gt;:<port>/<vdir>/<collectionName>


So for the new TFS10 on Codeplex, it looks like this:


https://tfs.codeplex.com:443/tfs/tfs10

IoC: Registering Concrete Types for Interfaces

One drawback to the OpenNETCF.IoC framework was the difficulty in making object generation loosely coupled.  This is especially true when object types you want to create change depending on your runtime environment.  For example let’s say we have an interface IAccelerometerService.  Different devices have different implementations, and the emulator and your integration tests don’t even have hardware so they need a simulator.  So you create some classes that derive from the interface like this:


public interface IAccelerometerService
{
}

public class DeviceAAccelerometer : IAccelerometerService
{
// handles the accelerometer by using APIs for device A
}

public class DeviceBAccelerometer : IAccelerometerService
{
// handles the accelerometer by using APIs for device B
}

public class SimulatedAccelerometer : IAccelerometerService
{
// simulates an accelerometer (emulator, test use, etc)
}


That’s all well and good, but let’s say we have a generic infrastructure module that does the object creation and injection.  We don’t want it to have to know about the concrete class types. They might be in separate assemblies that may not even exist – you certainly don’t need (or want) to ship emulator implementation for your hardware. 


How would you handle this? The IoC framework doesn’t like the following construct:


RootWorkItem.Items.AddNew<IAccelerometerService>();


Because it has no idea what concrete type you want it to create.  In this case it will throw an IOCException.


Today I added a “registration” process to the framework.  You now can do the following:


RootWorkItem.RegisterType(typeof(SimulatedAccelerometer), typeof(IAccelerometerService));


This tells the RootWorkItem that when you call to create an item of type IAccelerometerService, it should actually create an object of type SimulatedAccelerometer.


Each ManagedObjectCollection (so Items, WorkItems, SmartParts and Workspaceas) keeps track of its own Dictionary of type mappings and calling RegisterType on a given WorkItem calls the registration for each.  You can explicitly call RegisterType on any one of the collections directly and “override” an existing registration.  This means that you could have Items create one type and SmartParts create another type for the same interface.  I’m not sure when you’d ever want to do that, but I’ve provided for it.


Hopefully this makes the IoC framework a little more friendly, especially for testing (which is already painful enough for devices), and helps you, as a developer, develop your solutions faster without having to think about the underlying framework.