We have a (weird?) requirement to create X number of instances of the same class and we are using Ninject for IoC. Obviously we can do this manually by requesting objects of the same type multiple times:
for (var i = 0; i <= 10; i++)
{
var obj = _kernel.GetService(typeof(MyType));
...
}
This works as expected, but right now we have to access the kernel in our code to do this and that 'smells'. I'd prefer to handle this in the binding, sort of like the InRequestScope stuff.
To add a bit of complexity to all this we also specify the number of instances on the object it self, so the code above is actually closer to this: var obj = (MyType)_kernel.GetService(typeof(MyType));
for (var i = 0; i <= obj.NumberOfInstances; i++)
{
var obj = _kernel.GetService(typeof(MyType));
...
}
And one final thing to really make it messy; we use Ninject Conventions to bind the implementations to a base: var assemblies = AppDomain.CurrentDomain.GetAssemblies();
this.Bind(x => x
.From(assemblies)
.SelectAllClasses()
.InheritedFrom<BaseMyType>()
.BindAllBaseClasses());
The implementation I would love to be able to use is this:
this.Bind(x => x
.From(assemblies)
.SelectAllClasses()
.InheritedFrom<BaseMyType>()
.BindAllBaseClasses()
.Configure(syntax => syntax.InMultipleScope()));
But this may or may not be possible or a good idea...
Has anybody done anything like this? Or perhaps you can see a different way of doing it?
Details on requirement: We create multiple threads in a single Azure Worker Role and it would be beneficial to run multiple copies of the same code.