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

5 thoughts on “The OpenNETCF.IoC Framework: Items and Services”

  1. Nice work. Are those InjectionConstructor/ServiceDependency attributes mandatory or is it possible to inject "by convention" public constructors and setters? I find the attributes rather annoying…

    Like

  2. The attributes are required unless it’s a default, parameterless ctor. The reason behind this is the case of multiple ctors. How would the framework know which to use? Rather than making it guess, I force the developer to tell the framework.

    Like

  3. Hi Chris, the mandatory attributes force you to reference an external assembly (the one where the attributes are defined) just to point which constructor should be used.
    In CompactContainer I’ve used the convention that the constructor with the greater number of dependencies that can be satisfied is the one that is used.
    This approach helps in keeping your classes clean and works ok most of the time.

    Like

  4. While I applaud the effort, there are two problems:
    1. You have to reference the assembly to get things like RootWorkItem as well, so it’s not like you’re losing much
    2. By not having the attribute, the code is harder to read. How do I know what ctor it will call? How will the *next* guy know? How will he know injection is used at all? Code must not just work, it also has to be readable.

    Like

  5. Hi Chris, interesting stuff. However, I did notice that in a few of the examples of an InjectionConstructor, the second parameter is another MenuForm instance, where it should presumably be a SettingsForm?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s