More Bug fixes and improvements to OpenNETCF.IoC Framework

I’ve pushed up a new set of features and fixes for the OpenNETCF.IoC Framework as well as rolled a new release. See the Project Site for full details on what changed, but the general feature additions are that the framework now supports loading modules from configuration XML (you can now really decouple your app modules) and I added support for a DeckWorkspace and all the trappings around starting your app from a workspace.

Adding Model View Presenter to OpenNETCF.IoC Framework

I’m in the middle of adding a Passive View Model-View-Presenter(MVP) framework to the OpenNETCF IoC Framework.  I just checked in a working version (it’s in the source downloads, not as a release).  If you’re interested and want to have a say in how it ends up, go ahead and download it and give me your feedback.  There’s a simple usage example in source control.

OpenNETCF.IoC Framework source published

I’ve finally got the CodePlex project set up for the OpenNETCF.IoC framework, so that is now the “official” place to get it.  One thing to note is that my original intent was to publish under a Public Domain license, but evidently it’s not one of the options in CodePlex (I’ll email them and see what I can do about that).  In the meantime I set it to what looks to be the most permissable license they had – the MIT license.

Part III: The OpenNETCF.IoC Framework: Events

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events (this article)
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


In the Part II of this series we looked at how the OpenNETCF.IoC framework provides dependency injection for the lists of Items and Services and if you look at the sample application that ships with the framework you’ll see that the application creates and displays 3 separate Froms and a Service without a single call to the ‘new’ operator anywhere in the solution and, more importantly, without having to pass object references around yourself.

While I find that both fun and useful, the real thing I love about the OpenNETCF.IoC framework (and the SCSF that it’s modeled after) is the implementation of inversion of control through event publication and subscription.

A New Paradigm for Events

In the traditional managed development, an object exposes an event, something like this:

public event EventHandler OnMyEvent;

And when a subscriber wants to get notified of that event, they add a handler delegate like this:

publisherInstance.OnMyEvent += HandleOnMyEvent;

void HandleOnMyEvent(object sender EventArgs args)
{
  // do something useful here
}

That’s all well and good, but in my mind there are two problems with it. First it’s just plain ugly.  I have code in two places, first to attach the event, and second to handle it.  I like to keep related code close together, and this coupling of attaching the handler and the delegate implementation makes that hard (unless you use anonymous delegates). 

The second, and far worse, problem is that it requires that you have the instance of the event publisher to wire this up.  In some cases this is fine, but in others it seems rather pointless.  Let’s go back to one of our early examples of People and Cars and extend it ever so slightly.  We’ll add an event to the Car class :

public delegate void WreckHandler(ICar car);

class Car : ICar
{
  public event WreckHandler OnWreck;
}

And let’s say we have a specialized person – a PoliceOfficer – and he’d like to know any time there is a car wreck.

class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}
}

How would we wire this up?  Should we pass every Car instance in town to the officer so he can wire up the event?


class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}

  public void WatchCar(ICar car)
  {
    car.OnWreck += HandlerCarWreck;
  }
}

When would we call this?  Every time a Car instance is created?  How would the new Car instance know about the PoliceOfficer?  What if we have multiple Officers?  You can see that this gets real ugly, real fast.  Wouldn’t it be nice if any PoliceOfficer could just listen for the OnWreck event globally and any time any Car instance raised it, he would get notified?  Well that’s what the OpenNETCF.IoC framework’s eventing structure is all about. You publish and subscribe to events based on a unique string name for the event of interest.

So for the event publisher, the Car in this case, we use the same event definition but we add a simple attribute:


class Car : ICar
{
  [EventPublication(“CarWreck”)]
  public event WreckHandler OnWreck;
}

The important piece here is the text string that is sent in to the EventPublication attribute.  It can be any string at all, but it’s that string that event subscribers will use.

Over on the subscriber end it, hooking up the event looks like this:

class PoliceOfficer : Person
{
  [EventSubscription(“CarWreck”, ThreadOption.Caller)]
  public void HandleCarWreck(ICar car) {…}
}

Notice that I’m using the same text string in both.

Now there are a few important notes on using events in the OpenNETCF.IoC framework.  First all of the objects (publishers and subscribers) have to be actually in the framework (in either the Items or Services collection).  In fact with the version of the Framework that ships as I write this, the objects actually have to be created by the framework.  This means that if you create the object manually and then use the Add method to get it into the collection (as opposed to calling AddNew or using an InjectionConstructor or ServiceDependency), then the events won’t get wired up.  I intend to fix this in a future version, but if you pull down the code today, be aware of that limitation.

The second note is in relation to the subscriber.  You’ll see that the EventSubscription attribute takes a ThreadOption as a second parameter.  The idea behind this parameter is that it should dictate the thread on which the handler runs – either in the context of the caller or in the context of the UI.  Well that attribute, for now, is just a placeholder.  It’s not actually used anywhere, so don’t be surprised if your worker thread raises an event and your subscriber tries to update the UI and gets an exception whining about the use of Control.Invoke.  Again, this is something I intend to complete but when I looked at the options of releasing the framework either earlier with a few missing features or later and feature complete, I thought that just getting it out would be a lot more useful.


Next up: Looking at the performance implications of all of this IoC and DI stuff

The OpenNETCF.IoC Framework: Items and Services

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services (this article)
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


The OpenNETCF.IoC Framework

Since I don’t expect that everyone has used the SCSF and since the OpenNETCF IoC framework is a very small subset, let’s walk through what it is and how it works.  First, the OpenNETCF.IoC framework is based on the concept of “Components.”  A Component is simply an instance of a class and our framework has two flavors of Components: an Item and a Service.  Generally speaking, the difference between an Item and a Service is that an Item is a uniquely-named instance of a Type (so you can have any number of them provided each instance has a unique name) whereas there can only be one Instance of a service per registered type (it acts somewhat like a Singleton).

Both Items and Services are contained as collections in a root container called the RootWorkItem (a name that comes from the CAB framework).  Let’s take a look more in depth at each of these components and how you might use them together.  For this example we’ll get a little more concrete that the Cars and People example from before, and instead look at classes more actual applications might use.

Items

As I mentioned, Items are simply uniquely named instances of objects.  They can be of any Type – the Items collection doesn’t need to contain only a set of a specific type.  The Items are contained, conveniently enough, in the RootWorkItem.Items collection.  So exactly what advantages to we gain by putting our items in this collection?  The primary benefit is that the RootWorkItem becomes an instance manager and, as we’ll see in a little bit, it can also be a factory.

Let’s assume that our application contains the following Forms: MenuForm, EntryForm and SettingsForm and to make things simple, we’ll assume that they are named with their type name.  If we have these forms in the IoC framework, then any time we need to reference one of them we can simply do something like this:

 

desiredForm = RootWorkItem.Items[“EntryForm”];

 

and ta-da, we get the instance of the Form.  We don’t need to pass around a reference to it or store it in some other application global location.  So that’s pretty useful right there.  But the RootWorkItem really is just an application global, right, so it must provide some other benefit.  Well it’s also a factory.  If we want to create the entry form we can use a basic create-and-insert mechanism like this:

EntryForm form = new EntryForm();
RootWorkItem.Items.Add(form, “EntryForm”);

But that really isn’t all that interesting.  Where it gets interesting is that you can let the framework do the construction for you by simply giving it a Type and name (the name is actually optional, as the framework will assign it a GUID if you don’t provide one):

RootWorkItem.AddNew<EntryForm>(“EntryForm”);

That’s handy.  No need to call the object contructor to get an instance and then stuff it into the collection.  Less code is always a good thing.  But what else can it do (right now I’m feeling a bit like Ron Popeil)?

Well that’s not all!  Where it gets fun is in its ability to do injection.  This requires a little more complex of a scenario.  Let’s assume that the MenuForm requires an instance of both an EntryForm and a SettingsForm.  Something like this:

class MenuForm
{
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}
 

Well the OpenNETCF.IoC framework can actually do these injections for you – all you have to do it provide it a little direction with attributes.  If we simply decorate the constructor with the InjectionConstructor attribute, the framework will search the Items collection for existing items of the proper type to inject.  So the MenuForm looks like this:

class MenuForm
{
[InjectionConstructor]
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}

And construction now looks like this:

RootWorkItem.AddNew<SettingsForm>(“SettingsForm”);
RootWorkItem.AddNew<EntryForm>(“EntryForm”);
RootWorkItem.AddNew<MenuForm>(“MenuForm”);

And the magic of the OpenNETCF.IoC framework will inject the first two instances into the third.  An interesting note here is that the Injection Constructor does not have to be public.  The OpenNETCF.IoC framework looks for internal and private constructors as well so you can actually create objects that can only be generated via injection if you wish.

Of course the framework also supports Injection Methods as well, in the event that an InjectionConstructor doesn’t meet your needs:


class MenuForm
{
  public MenuForm() {…}

[InjectionMethod]
void InjectEntryForm(EntryForm entryForm) {…}

[InjectionMethod]
void InjectSettingsForm(SettingsForm settingsForm) {…}
}

But wait, there’s more!  In the examples so far the RootWorkItem.Items collection must contain the SettingsForm and EntryForm before the MenuForm is created.  Well what if we are lazy and don’t even want to do that?  Well the OpenNETCF.IoC framework can handle that too.  Just add the CreateNew attribute like this:

 

class MenuForm
{
[InjectionConstructor]
  public MenuForm([CreateNew]EntryForm entryForm, [CreateNew]MenuForm menuForm) {…}
}

 

And the framework will create a new instance of the Type if it can’t find it in the Items collection. Construction of all three objects and injecting them now looks like this:

 

RootWorkItem.AddNew<MenuForm>(“MenuForm”);

 

Extremely simple and clean.

Services

The RootWorkItem also contains a collection of Services.  A Service is very similar to an Item except for the fact that there can only be one service of any given registered type (we’ll covered what “registered” means in a moment).  The collection provides a very similar set of methods and attributes as items.  Again, let’s consider a more concrete example.  Assume your application has a class that handles reading and setting configurations.  There really would only be one instance of this class and in a lot of classic cases people would use the global-wrapped-in-a-new-name called a Singleton.

In the OpenNETCF.IoC framework this would be a service.  Since there can only be one pre registered type, there’s no need to name a Service – the registration type becomes the identifier.  So as a simple construct/add/retrieve a Service operation would look  like this:


Configuration config = new Configuration();
RootWorkItem.Services.Add<Configuration>(config);

Configuration retrievedConfig = RootWorkItem.Services.Get<Configuration>();

As with the Items collection, there is a lot more power and convenience in the framework.  First, we can have the framework do construction for us:

 

RootWorkItem.Services.AddNew<Configuration>();

 

 

Like the Items collection, InjectionConstructor or InjectionMethod attributes can be used to control which constructor for the service class gets called.

The OpenNETCF.IoC framework also offers lazy loading of services, so the service instance isn’t actually created until it is first accessed (instead of when it’s added).

 

RootWorkItem.Services.AddOnDemand<Configuration>();

 

 

We saw earlier that the OpenNETCF.IoC framework would walk the Items collection looking for instances to use during injection.  Well what if an object depends on a Service rather than another Item?  The framework also provides a mechanism for that as well using the ServiceDependency attribute.  So to inject a Service into a consumer class using Constructor Injection it would look like this:

class ServiceConsumer
{
[InjectionConstructor]
  public ServiceConsumer([ServiceDependency]Configuration config) {…}
}

And of course there is a way to do setter injection instead of constructor injection.  Here it injects into a property instead of using a method like the Items collection:

 

class ServiceConsumer
{
  public ServiceConsumer() {…}

[ServiceDependency]
  public Configuration Config { set; get; }
}

 

And if you want the framework to construct the service if it doesn’t already exist, you simply set the EnsureExists member of the ServiceDependency attribute like this:


[ServiceDependency(EnsureExists=true)]
public Configuration Config { set; get; }

The only other aspect of a Service that an Item does not have is a “registration type”.  This allows you to register a service instance as a type other than its actual base type.  For example you may have a Configuration class that you want to register as a service, but you want to register it as an IConfiguration (this would allow consumers to extract the service by the interface type without ever knowing about or having a reference to the concrete implementation).

 


Up next: The OpenNETCF.IoC Framework: Event Publication and Subscription

Inversion of Control and the Compact Framework (Part I)

Articles in this series
Part I: Inversion of Control and the Compact Framework (this article)
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


Introduction

Periodically the software industry goes through a shift in underlying programming practices.  In the 80s the shift was from procedural code to object oriented.  In the 90s we saw the rise of things like “extreme” and “agile” programming.  Recently I’ve seen a shift toward using dependency injection (DI) and inversion of control (IoC).  They’ve been around long enough now that I think they’ll stick, and since any programmer should try to maintain some level of understanding of the latest technologies, I decided to dive into them.

What came out of my investigation were the following:

1.       I was already doing a lot of the stuff, I just didn’t know it

2.       That there really isn’t a reasonable framework in existence for the Compact Framework

3.       Dependency Injection and Inversion of Control, when followed well, can greatly improve extensibility, maintainability and testability of code.

4.       My own IoC framework

Definitions

Before we can talk about all of the benefits of using a framework for Dependency Injection and Inversion of Control, we really need to define them. 

Dependency Injection

Though the name sounds complex, Dependency injection really is what the name implies and is really simple, but explaining it in abstract terms tends to get convoluted.  For example, it could be defined as “with dependency injection you inject dependent objects into the object which depends on them.” Doesn’t really roll of the tongue, does it?  I read that I tend to see “blah, blah, object, blah, depend, blah” and want to move on to something else altogether.  But really, it is simple.  So let’s use an actual example and a picture.

Let’s say we have a couple classes,  Car and Person, and a person can own and drive a car. So it’s something like this:

class Car
{
  public Car() {…}
}

class Person
{
  private Car m_car;

  public Person() {…}

  public void Drive () {…}
}

Now the question here is how does the Drive method “get” or “know” what car to Drive?  One way would be to have the Person instance create the car along these lines:

public Person()
{
m_car = new Car();
}


So the Person class knows what its dependency is.  It knows at compile time that it needs a Car and creates it.  That’s all well and good, and sure, it work, but it’s certainly not extensible.  To make it a little more extensible, we could use an interface for the Car instead:

class Person
{
  private ICar m_car;

  public Person()
{
    if(this.IsAMoparGuy)

      m_car = new ShinyDodgeChallenger();
    else
m_car = new RustBucket();
}
}

 

This is a bit more extensible – the Person has some opportunity to decide what type of car it wants, but it still puts that decision in the Person class and the Person class still has to know about the concrete types of Car. So how do we make it even more extensible so that Person needs to only know about the interface?  Simple – we pass in the object.  That can be done, generally speaking, in two ways.  Either in the constructor:

class Person
{
  private ICar m_car;

  public Person(ICar car)
{
m_car = car;
}
}

Or using a method to set it:

class Person
{
  private ICar m_car;

  public Person() {}


  public SetCar(ICar car)
{
m_car = car;
}
}

It’s very likely that you’ve used patterns like this in the past, and in fact these are dependency injection.  The first is called “constructor injection” and the second is called “method injection.”  I’ve also seen references to “property injection” which you can probably guess sets the dependency using a Property instead of a method, but a Property really is nothing more than syntactic sugar around a pair of methods.  If you really want to consider it separate, then we can lump the Property and Method injections into something I’ll call “setter injection.”

Inversion of Control

Inversion of Control is a lot like Dependency Injection in that the name puts me off immediately because it sounds like an attempt to use overly large words to describe a likely simple thing, and indeed it is.  In “old school” programming you might have an object (like a Person) that controls another object (like a Car) and when you want to know if some state has changed, you simply query it.

So the Person instance might do something like this

if(m_car.HasCrashed) Call911();

Well Inversion of Control simply turns that around.  Instead of us asking the object for state, the child object (the Car in this example) will inform us of a change.  Sound familiar?  .NET events and delegates are a classic, and really often used, case of Inversion of Control.

So you might hook it up like this

m_car.OnCrash += new CrashHandler(
    delegate { Call911(); }
);

It’s nothing more complex than that.

IoC and the Compact Framework

When I started out looking into IoC and DI, I was a little put off.  I dislike following programming fads or chasing after some technology simply because it’s all the rage and there are conferences touring the country talking about them.  But I was working on a desktop project and a friend said that I should check out Microsoft’s Smart Client Software Factory (or SCSF) as he thought it would be a good framework to achieve the goals we were after.

Well it turns out that SCSF is built on Microsoft’s Composite UI Application Block (also called CAB) and together they really are just a library that provides a very robust IoC framework.  I’m currenly working on porting that desktop project to use the SCSF and it’s turning out to be very, very useful.

When I needed an IoC framework for the CF, I found that Microsoft’s Patterns and Practices team ported the CAB/SCSF framework a few years back.  I also quickly found out that the people who did the port appeared to do a literal port of the code.  So while it compiles and runs, it certainly does not take into consideration the limited memory and processor power of a typical Windows CE device.  A very common complain about the Mobile Client Software Factory is that its performance sucks.  And I can attest to that.  It does suck.

So what to do?  There are a couple (and really only two that I could find) IoC frameworks that claim to be CF compatible.  I looked at them briefly, but I pretty quickly abandoned them because I really don’t feel like learning the object model for a whole new framework.  I’m using the SCSF and I’m comfortable with it, and I don’t like having to constantly have to think about object models depending on what my code targets.  I also like to keep my code as reusable as possible, and changing frameworks certainly wouldn’t help on that front.

So what I decided to do was to build my own framework based, mostly, on the object model of the SCSF.  The goal was to implement only the bare minimum of what I needed and to build it specifically considering that it would be used on CE devices. What I ended up with is a simple, lightweight dependency injection framework that I called OpenNETCF.IoC. 


Up Next: The OpenNETCF.IoC Framework: Items and Services