Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I usually make a factory (or provider as you have here) with something like this:</p> <pre><code>public class ConverterFactory : IConverterFactory { private readonly IResolutionRoot resolutionRoot; public ConverterFactory(IResolutionRoot resolutionRoot) { this.resolutionRoot = resolutionRoot; } public IConverter&lt;TValue, TConverted&gt; CreateConverter() { Type converterType = typeof(IConverter&lt;,&gt;).MakeGenericType(typeof(TValue), typeof(TConverted)); return this.resolutionRoot.Get(converterType); } } </code></pre> <p>I know we're not really supposed to be using Ninject to create things at runtime but really sometimes it's unavoidable. To get the singleton behaviour, just define <code>InSingletonScope()</code> as normal.</p> <p>If the types weren't generic then you can inject all implementations of the interface instead of the <code>IResolutionRoot</code> then pick one at runtime. I have a parser factory a bit like this:</p> <pre><code>public class ParserFactory : IParserFactory { private readonly IEnumerable&lt;IParser&gt; parsers; public ParserFactory(IEnumerable&lt;IParser&gt; parsers) { this.parsers = parsers; } public IParser CreateParser(string someInput) { foreach (var parser in this.parsers) { if (parser.CanParse(someInput)) { return parser; } } } } </code></pre> <p>Ninject will automatically inject an <code>IEnumerable</code> containing all concrete implementations of the interface, so adding new implementations is as simple as adding a mapping. I don't know how to do that with generic types though since you can't say <code>IEnumerable&lt;IConverter&lt;,&gt;&gt;</code>.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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