»
S
I
D
E
B
A
R
«
StructureMap: IRepository and Test Data Injection
Jul 26th, 2009 by Josh Rivers

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 wonder
if I even know what I’m talking about. The problem with StructureMap, IoC, and dependency
injection really seems to be that the jargon for the patterns is so manifestly
true
that once you learn what the hell you are doing, you are completely
unable to stop talking about it in shorthand. And that shorthand makes absolutely
no sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Once
you do it, you’ll get it. Then you’ll be there and not be able to
explain to other people why you’re so right. It’s like being Tom Cruise and needing
to explain scientology.

Anyways.

I learned two things today. The first is how to hook all of my concrete generic repository
types together with their interfaces. I had been adding a line of configuration for
each 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 object
registry 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(T
entity)
{
return;
}
}

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

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

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

»  Substance: WordPress   »  Style: Ahren Ahimsa