Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about something along the folowing lines:</p> <pre><code>public delegate object VariableParamFactoryFunc(params object[] constructorParams); public class Factory { private Dictionary&lt;Type, VariableParamFactoryFunc&gt; _registeredTypes = new Dictionary&lt;Type, VariableParamFactoryFunc&gt;(); public void RegisterType&lt;T&gt;(VariableParamFactoryFunc factoryFunc) { _registeredTypes.Add(typeof(T), factoryFunc); } public T Resolve&lt;T&gt;(params object resolutionParams) { VariableParamFactoryFunc factoryFunc; if (_registeredTypes.TryGetValue(typeof(T), out factoryFunc)) { return (T)factoryFunc(); } else { return default(T); } } } </code></pre> <p>Then you would use it by first registering factory functions: (e.g.)</p> <pre><code>var factory = new Factory() // or you can turn it into a singleton, this is just for demonstration factory.Register&lt;IMyInterface&gt;((a, b, c) =&gt; new ConcreteImplementation(a, b, c)) factory.Register&lt;CustomClass&gt;((a, b) =&gt; new CustomClass(a, b)); </code></pre> <p>and then by actually resolving and consuming those factory functions: </p> <pre><code>IMyInterface myInterface = factory.Resolve&lt;IMyInterface&gt;(1, "string", 2.412); CustomClass customClass = factory.Resolve&lt;CustomClass&gt;("param1", 1234); </code></pre> <p>This should allow you flexibility in Resolving constructors with variable number of parameters without paying the performance penalty of Activator.CreateInstance or Reflection, but you loose in type safety since all parameters will be cast to objects and you will need to cast them back to the right type in the factory function</p> <p>Good luck!</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