Note that there are some explanatory texts on larger screens.

plurals
  1. POStack overflow when resolving services with Ninject
    primarykey
    data
    text
    <p>I'm trying to resolve a known fixed list of Foo services (in singleton scope) using NInject; this resolution happens in a FooProvider's constructor. The problem is that each Foo will need this provider as well. </p> <pre><code>public interface IFoo { } public interface IFooProvider { } public class Foo : IFoo { private readonly IFooProvider _provider; public Foo(IFooProvider provider) { _provider = provider; } } public class FooProvider : IFooProvider { private List&lt;IFoo&gt; _allFooServices; public FooProvider(IKernel kernel) { _allFooServices = kernel.GetAll&lt;IFoo&gt;().ToList(); } } public class Program { private static void Main(string[] args) { var IoC = new StandardKernel(); IoC.Bind&lt;IFoo&gt;().To&lt;Foo&gt;().InSingletonScope(); IoC.Bind&lt;IFooProvider&gt;().To&lt;FooProvider&gt;().InSingletonScope(); var foo = IoC.Get&lt;IFoo&gt;(); } } </code></pre> <p>There is a logical cyclic loop here, and obviously the stack overflow shows its going down it. However, I have both interface bound to singletons. </p> <p>Thinking about it; we try to resolve IFoo, which then needs resolution of IFooProvider, itself needing a list of IFoo... but we haven't resolved for any IFoo singletons yet because we're still trying to resolve it!</p> <p>So how could I work around this? </p> <p>[Edit] Possible solution; delay buffering of IFoo service instances. </p> <pre><code>public FooProvider(IKernel kernel) { _kernel = kernel; } public IFoo Find(object context) { if (_allFooServices == null) _allFooServices = _kernel.GetAll&lt;IFoo&gt;().ToList(); return _allFooServices.Where(... </code></pre> <p>[Why?]</p> <p>The general idea is to avoid the service locator pattern, as I've seen it described as an anti-pattern. So, rather than try to resolve services through the dependency injector during run time; you try to get a list of services during setup. The problem with this though, is that if any of your services want to find other services, you have the above problem.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload