Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing a Service Locator with injected variations of Generic Type
    text
    copied!<p>I have the following: </p> <pre><code>public interface IConverter&lt;TValue, TConverted&gt; { } public interface IConverterProvider { IConverter&lt;TValue, TConverted&gt; GetConverter&lt;TValue, TConverted&gt;(); } </code></pre> <p>With an example binding at setup: </p> <pre><code>Bind&lt;IConverter&lt;System.Int32, System.String&gt;&gt;().To&lt;Int32ToStringConverter&gt;(); Bind&lt;IConverter&lt;System.Guid, System.String&gt;&gt;().To&lt;GuidToStringConverter&gt;(); </code></pre> <p>So I have a collection of fixed converters and no duplicate bindings. </p> <p><strong>[Question]</strong> My question is how do I go about implementing the IConverterProvider and injecting a dictionary of available bindings mapped to singletons? Or in other words, how to avoid the run-time service-locator pattern. </p> <p>Currently I'm just using the NInject kernel to resolve each time, but I believe this an anti-pattern. What I would like is something like this: </p> <pre><code>public class ConverterProvider : IConverterProvider { private Dictionary&lt;Type, object&gt; _converters; public ConverterProvider(Dictionary&lt;Type, object&gt; converters) { _converters = converters; } public IConverter&lt;TValue, TConverted&gt; GetConverter&lt;TValue, TConverted&gt;() { var fullTypeResolve = typeof (IConverter&lt;,&gt;).MakeGenericType(typeof (TValue), typeof (TConverted)); return _converters.Where(x =&gt; x.Key == fullTypeResolve).Select(x=&gt;x.Value).Cast&lt;IConverter&lt;TValue, TConverted&gt;&gt;().Single(); } } </code></pre> <p>But this effectively requires that I'm able to resolve and get a list of all IConverter&lt;,> from the dependency injection kernel, and my previous attempts of doing this from NInject haven't been successful. </p>
 

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