StructureMap: IRepository and Test Data Injection

I Love StructureMap! It’s wonderful. What a way to compose your code together easily,precisely, and consolidatedly (!!). When I put a sentence like that together, I wonderif I even know what I’m talking about. The problem with StructureMap, IoC, and dependencyinjection really seems to be that the jargon for the patterns is so manifestlytrue that once you learn what the hell you are doing, you are completelyunable to stop talking about it in shorthand. And that shorthand makes absolutelyno sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Onceyou do it, you’ll get it. Then you’ll be there and not be able toexplain to other people why you’re so right. It’s like being Tom Cruise and needingto explain scientology.

Anyways.

I learned two things today. The first is how to hook all of my concrete generic repositorytypes together with their interfaces. I had been adding a line of configuration foreach repository. Now my test code looks like this:

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(ListRepository<>));

And my production code:

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(LlblRepository<>));

That’s easy!

The other thing I learned is that I can happily and easily inject data into my objectregistry for testing purposes. I have an in-memory repository implementation built.All it needs is data.

public class MemoryDataSource{private Dictionary<Type, IQueryable> data;public MemoryDataSource(Dictionary<Type, IQueryable>data){this.data = data;}public IQueryable GetQueryable(Type type){return this.data[type];}}public class ListRepository<T>: IRepository<T>{private MemoryDataSource source;public ListRepository(MemoryDataSource source){this.source = source;}public IQueryable<T> GetSource(){return ((IQueryable<T>)source.GetQueryable(typeof(T)));}public void SaveEntity(Tentity){return;}}

Now all I need to do is build a Dictionary<> keyed on the entity object typeand fill it up with data. Once I’ve done that, I just pass it into the StructureMapregistry like this:

ObjectFactory.Inject<Dictionary<Type, IQueryable>>(dataSource);

Now I can have ObjectFactory construct my object under test and it’s got just thedata I need it to have.

Advertisements

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