Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.</p> <p>So, you want to use DI to defer that choice to one that can be configured by the client.</p> <p>This is some pseudocode (roughly based on Unity):</p> <p>You create a logging interface:</p> <pre><code>public interface ILog { void Log(string text); } </code></pre> <p>then use this interface in your classes</p> <pre><code>public class SomeClass { [Dependency] public ILog Log {get;set;} } </code></pre> <p>inject those dependencies at runtime</p> <pre><code>public class SomeClassFactory { public SomeClass Create() { var result = new SomeClass(); DependencyInjector.Inject(result); return result; } } </code></pre> <p>and the instance is configured in app.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name ="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/&gt; &lt;/configSections&gt; &lt;unity&gt; &lt;typeAliases&gt; &lt;typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /&gt; &lt;/typeAliases&gt; &lt;containers&gt; &lt;container&gt; &lt;types&gt; &lt;type type="MyAssembly.ILog,MyAssembly" mapTo="MyImplementations.SqlLog, MyImplementations"&gt; &lt;lifetime type="singleton"/&gt; &lt;/type&gt; &lt;/types&gt; &lt;/container&gt; &lt;/containers&gt; &lt;/unity&gt; &lt;/configuration&gt; </code></pre> <p>Now if you want to change the type of logger, you just go into the configuration and specify another type.</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