Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is an interesting problem. How can you dependency inject re-usable assemblies that do not have an entry point. <em>I would really like to see other people's answer.</em></p> <p>Dependency injection is the responsibility of the <em>entry-point assembly</em>. Yet, if you have a lot of classes and assemblies each needing DI, then it is possible that they are left-off for some classes/assemblies and the task becomes onerous.</p> <h1>Solution One</h1> <p>Using convention over configuration. You stick to a rule of class <code>Foo</code> implementing <code>IFoo</code>, etc. A lot of DI frameworks have the means to set it up using convention.</p> <h1>Solution two</h1> <p>Above solution does not solve all problems since sometimes you need to parameterise the setup of the injection. Here is how I have solved the problem (especially for those assemblies loaded by <strong>MEF</strong> and this is for <code>AutoFac</code>):</p> <p><strong>Created an interface <code>IIocInstaller</code> where container (or builder is passed)</strong></p> <pre><code>public interface IIocInstaller { void Setup(ContainerBuilder builder); } </code></pre> <p><strong>Created an assembly attribute that flags assemblies needing DI:</strong></p> <pre><code>[AttributeUsage(AttributeTargets.Assembly)] public class ExportAssemblyAttribute : Attribute { } </code></pre> <p><strong>In each assembly, I create a class that sets up DI:</strong></p> <pre><code>[assembly: ExportAssembly] namespace This.That { [Export(typeof(IIocInstaller))] public class IocInstaller : IIocInstaller { public void Setup(ContainerBuilder builder) { .... } } } </code></pre> <p>Then in the entry point, I have a common code which looks through all loaded assemblies (including MEFed ones) that have the assembly attribute and then look for the type implementing the <code>IIocInstaller</code> and then call Setup on them.</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