开发者

How can i initialize some Dependency Injected instance?

开发者 https://www.devze.com 2023-01-18 08:05 出处:网络
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 request

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.


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?


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...

How can i initialize some Dependency Injected instance?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消