views:

42

answers:

2

Hi folks,

I'm using StructureMap DI/IoC and I've got is a generic InMemory repository. Works great. I was wondering if it's possible to define the initial data which each repository holds, when it's requested?

Now, the first reaction is to do this in the constructor of the class - but I'm using a Generic Repository .. so i don't know what type of class will be instantiated. Next, I could subclass the GenericRepository and then create a constructor - sure :) That would work .. but i was trying to avoid creating a single class for each repository, when the GenericRepository is more or less doing everything I want :) (yes, there's some specific instances which I do subclass, etc.. but lets keep this post, simple).

So, is there a way to say

  1. Create an instance of InMemoryGenericRepository when ever an IRepository is requested
  2. Now, call this static method (which populates that Repo instant) : Foo(IRepository repository) { ... } which of course passes in the instance that was just created by StructureMap.
A: 

I really recommend subclassing it. That's the object-oriented way to go, after all.

But in any case, even if your repository is generic, can't you just pass a generic collection into the constructor? Or am I misunderstanding something?

Zor
Ah of course :) I can add that to the `generic` constructor. Wikid :) I'll give that a go...
Pure.Krome
A: 

The answer is StructureMap Inception :: .OnCreation(Action).

so with my example, above...

For<IRepository<Post>>()
    .Use<InMemory.GenericRepository<Post>>()
    .OnCreation(x => x.Add(InMemoryData.CreatePostStubs());

Firstly, the static method CreatePostStubs() returns an ICollection<Post> which then gets passed into a method called Add to my newly created GenericRepository<Post> instance. This, in effect, adds all the stubs to my in-memory repository.

FUNKY !!

So funky, it's time for a Funky Cold Medina...

alt text

Cheers to @Zor for starting me off on the right direction ...

Pure.Krome