Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ninject (or other IoC) with Task scope?

I'm not sure the TPL surfaces enough for this to be viable, and as such, feel free to just point out alternative patterns that work instead. :)

I'm trying to figure out if I can use Ninject for ctor-injected dependencies that should ideally be scoped to a particular root/parent Task instance.

It's somewhat similar to asp.net request scope, but in this scenario, it's a console app that's creating N different Tasks that will run in parallel. I'm wondering if there's an ability to get Ninject to do the runtime dependency injection based on each of those root Task instances such that the object graph created as part of each task shares the same instances of a given interface, but the different tasks all have separate instances.

Thanks!

[EDIT] continuing to search, it looks like the InNamedScope might be the right answer based on the description of "define that objects are the scope for their dependencies"

like image 411
James Manning Avatar asked May 18 '12 16:05

James Manning


1 Answers

If I understand your question correctly, InNamedScope is a good choice. The other alternative is InCallScope. This blog post has a good discussion of the differences:

The named scope lets you define on a binding that the object created by the binding is the scope for other objects that are part of the object tree that is injected into the created object.

Let us see how this works on an example. Imagine that you are creating an Excel like application that has multiple worksheets....

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

Here, the SheetDataRepository uses the ExcelSheet that's in scope. The article explains in greater detail.

like image 109
neontapir Avatar answered Oct 27 '22 02:10

neontapir