Pete Montgomery
Pete Montgomery

Reputation: 4100

Pass dynamic parameters to factory / composition root in Ninject (or perhaps any container)

Here is an example.

foreach (var doc in documents)
{
    var processor = this.factory.Create();
    processor.Process(doc);
}

The factory internally calls kernel.Get<IDocumentProcessor>().

I'd like all the document processor's dependencies' lifetimes to be "scoped" to this composition root. This configuration seems to do what I want:

kernel.Bind<IEntityContext>().To<EntityContext>().InCallScope();

Now each object graph rooted at the document processor has a unique, shared entity context for accessing the database. But this

  1. affects all entity contexts everywhere in the application (which may be ok, but seems hard to discover), and
  2. only seems to work for bindings known about statically.

I think my question is, how can I achieve the same scoping / lifetime management effect with "contextual" or dynamic information? Perhaps I want to have the document instance itself injected into all children of the new root:

    var processor = this.factory.Create(doc)
    processor.Process()

Thanks!

Upvotes: 1

Views: 739

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

With Ninject 3.0.0 you can do

kerne.Get<IProcessor>(new ConstructorArgument("doc", doc, true));

But to me there still seems to be a design flaw to have doc as a dependency of the processor. It would be better to create the processor once and reuse it for multiple documents by passing the document to the Process method. I still do not get what's the issue with this due to the fact that the question does not show the actual problem.

Upvotes: 1

Related Questions