Note that there are some explanatory texts on larger screens.

plurals
  1. POResolve automatic factory from named registration for generic type
    text
    copied!<ol> <li><p>Assume a simple interface:</p> <pre><code>public interface ICommandHandler&lt;T&gt; { void Handle(T command); } </code></pre></li> <li><p>Assume several implementations for different concrete <code>T</code>s like:</p> <pre><code>public class FooCommandHandler : ICommandHandler&lt;FooCommand&gt; { /*...*/ } </code></pre></li> <li><p>Assume a generic factory implementation of that interface:</p> <pre><code>public class FactoryCommandHandler&lt;T&gt; : ICommandHandler&lt;T&gt; { public FactoryCommandHandler(Func&lt;ICommandHandler&lt;T&gt;&gt; factory) { /*...*/ } /*...*/ } </code></pre></li> </ol> <p>Now, I want to register the factory handler from <em>3</em> to be the instance that is resolved when an <code>ICommandHandler&lt;T&gt;</code> is resolved.<br> My problem is that I fail to correctly register the other implementations so a factory for them can be resolved.</p> <p>Here is what I tried:</p> <pre><code>builder.RegisterAssemblyTypes(assembly) .Where(type =&gt; type.Name.EndsWith("CommandHandler")) .Named("concreteCommandHandler", typeof(ICommandHandler&lt;&gt;)); builder.RegisterGeneric(typeof(FactoryCommandHandler&lt;&gt;) .WithParameter( (p, c) =&gt; true, (p, c) =&gt; c.ResolveNamed("concreteCommandHandler", p.ParameterType)) .As(typeof(ICommandHandler&lt;&gt;)); </code></pre> <p>However, this fails, because there is no named <code>Func&lt;ICommandHandler&lt;SomeConcreteCommand&gt;&gt;</code> registered. Autofac seems to be unable to automatically create a factory in this case, <a href="http://code.google.com/p/autofac/wiki/DelegateFactories" rel="nofollow">which it normally supports</a>.</p> <p>How to fix the registration and achieve my goal?</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