I have a small class that creates a new instance of a data processor object each time it needs it. I am using injection for everything but I cannot figure out how to get an activated instance of IDataProcessingService without injecting the kernel.
Is there a better way to do this. I know I can make a static gateway rather than inject but I would think that is the same issue in a different skin.
public class DataProcessingManager
{
private readonly Dictionary<IDataProcessingRequest, IDataProcessingService> _activeProcessingServices;
private readonly IKernel _kernel;
public DataProcessingManager(IKernel kernel)
{
_kernel = kernel;
_activeProcessingServices = new Dictionary<IDataProcessingRequest, IDataProcessingService>(new DataProcessingRequestComparer());
}
public void ProcessFor(IDataProcessingRequest dataProcessingRequest)
{
if (!_activeProcessingServices.ContainsKey(dataProcessingRequest))
{
var _processingService = _kernel.Get<IDataProcessingService>();
_activeProcessingServices.Add(dataProcessingRequest, _processingService);
_processingService.ProcessingFinished +=
(sender, args) => _activeProcessingServices.Remove(dataProcessingRequest);
_processingService.Process(dataProcessingRequest);
}
}
}
EDIT 2 :
I had to change the accepted answer as the original suggested implementation was not creating new instances which is what I need. I know I could use the original answer by referencing the kernel but this is not what I want either. In the end the .ToFactory() convention in the new answer is the better way to do it.
I will contact the author of the extension and ask him to update the code sample as the Foo..Bar example is awkward to read.
If you want a new instance each time, you can use the Ninject Factory Extension to not depend on IKernel.
Using this extension, you can create a factory interface to create instances of IDataProcessingService, but you do not need to implement that interface. This extension can implement it for you (which under the hood will call to IKernel).
Factory interface…
Binding statement (which auto-generates the factory implementation at runtime)…