0

I'm trying to create a Ninject Factory using Ninject.Extensions.Factory like below:

 public interface  ICommandBatchFactory
    {
        CommandBatch GetCommandBatch(ILogger logger);        
    }

The problem is that I need "logger" to be injected to the instance / constructor (constructor pattern) and not to provide it explicitly in the GetCommandBatch of the factory.

Is this posibble with Ninject.Extensions.Factory? I' m trying to avoid referencing de Ninject Kernel or [Inject] annotations to not increase coupling.

  • Are you sure [you need a factory](https://cuttingedge.it/blogs/steven/pivot/entry.php?id=100)? – Steven Sep 26 '18 at 08:07
  • @Steven I would say yes but Im opened to different approaches. I use a factory to avoid referencing Ninject from low layers and to stop injection cascade in that point. – Cristian Abelleira Sep 26 '18 at 13:33
  • What is this "injection cascade" you are talking about and why is this a problem? And why can't you inject `CommandBatch` directly into the consumer's constructor? Why must the consumer supply an `ILogger` to the `ICommandBatchFactory`? – Steven Sep 26 '18 at 13:40
  • @Steven If you call Ninject Kernel.Get from your start class, all the dependencies are loaded and injected at same time in cascade following the dependency graph. Sometimes you dont want to instance all this objects at the same time for performance/resources reasons for example. If you use a factory you can stop this cascade injection because you decide when to create the instances of objects that that factory produce. But i think we are avoiding the main question. – Cristian Abelleira Sep 26 '18 at 13:49
  • Constructing complete object graphs should not be a performance bottleneck. Even though Ninject is, by far, the slowest DI Container in the field, this should still not be a problem while resolving object graphs in Ninject. If you need this because of performance reasons, I would still not suggest using a factory. Either change the DI configuration using different lifestyles, or use a Virtual Proxy. – Steven Sep 26 '18 at 13:53
  • @Steven thank you very much for your advice and the article about factories. I'll keep waiting if there is an answer for the concrete question. – Cristian Abelleira Sep 26 '18 at 14:07
  • Well, there are still a few unanswered questions from my side, such as: why do you need the `ILogger` to be passed into the factory by the consumer? Have you profiled the time it takes to construct a complete object graph where `CommandBatch` is injected into the consumer's constructor? If this is too much, might it be your classes have too many constructor arguments? Have you tried fixing this problem by using different lifestyles (scoped and singleton)? Instead of using a factory, have you tried using a Virtual Proxy for `CommandBatch` or a similar service to break the graph? – Steven Sep 26 '18 at 14:19

0 Answers0