Wednesday, April 01, 2009

Dependency injection using the ContainerModel on the Compact Framework

I mentioned a few weeks ago about the availability of an IoC framework for the Compact Framework here.

But a question related to this is how do you implement the dependency injection pattern with this IoC framework as IoC (Inversion of Control) and dependency injection go hand in hand with one another.

The most common way to implement dependency injection is via the constructor. Sadley this container doesn't work like Castle Windsor where Castle resolves dependencies for you automatically without you having to define then when registering the class. However the class still needs to be defined by an interface! With the device Container model you have to explicitly define your dependencies at registration. I'm ok with this as I'm happy to have a half decent container model for the Compact Framework.

So we have our CustomerRepository class that has a dependency on some Adapter (I just made this adapter up, it could do anything). The class looks like this:
public class CustomerRepository : Repository<Customer, int>, ICustomerRepository
{
private IAdapter _adapter;

public CustomerRepository(IAdapter adapter)
{
if (adapter.IsNull()) throw new ArgumentNullException("adapter");
_adapter = adapter;
}
}
Now, there are no methods in this class but the point is to show the dependency because later, we want to use the adapter class to do some... adapting.

So how do we set up the container to inject the adapter. Something like the following should do the trick:
using Microsoft.Practices.Mobile.ContainerModel;
var builder = new ContainerBuilder();
builder.Register<IAdapter>(adapter => new Adapter());
builder.Register<ICustomerRepository>(repository => new CustomerRepository(Resolve<IAdapter>()));
builder.Build(container);
Then from the consumer, we can code something like the following:
var customerRepository = ComponentContainer.Resolve<ICustomerRepository>();
We didn't have to declare our dependency, it was injected by the framework. We just resolved the adapter when we registered the repository. Of course you need to register this dependency with the framework first. You could use the concrete type here but this means if you change implementation details, you'd have to change the implementor in more than one place.

There we have it, dependency injection using an IoC container on the Compact Framework 3.5.

No comments: