Ninject (or other IoC) with Task scope?

I'm not sure if the TPL surface is enough for it to be viable, and so feel free to just point out alternative patterns that work instead. :)

I'm trying to figure out if I can use Ninject for ctor dependent dependencies, which ideally should be bound to a specific instance of the root / parent Task instance.

It is somewhat similar to the asp.net request area, but in this case it is a console application that creates N different tasks that will be executed in parallel. I am wondering if it is possible to force Ninject to inject dependencies at runtime based on each of these root instances of the task, so that the object graph created as part of each task has the same instances of this interface, but different tasks all have separate instances .

Thanks!

[EDIT] , continuing the search, it seems that InNamedScope might be the right answer based on the description "determine that objects are the scope of their dependencies"

+6
source share
1 answer

If I understood your question correctly, InNamedScope is a good choice. Another alternative is InCallScope . This blog post contains a good discussion of the differences:

The named area allows you to define the binding created by the object by the binding - this is the area for other objects that are part of the object tree that is entered into the created object.

Let's see how this works with an example. Imagine you are creating an Excel application that has multiple sheets ...

 const string ScopeName = "ExcelSheet"; Bind<ExcelSheet>().ToSelf().DefinesNamedScope(ScopeName); Bind<SheetPresenter>().ToSelf(); Bind<SheetCalculator>().ToSelf(); Bind<SheetDataRepository>().ToSelf().InNamedScope(ScopeName); 

Here SheetDataRepository uses ExcelSheet in scope. The article is explained in more detail.

+4
source

Source: https://habr.com/ru/post/916109/


All Articles