Here is a general example. You need to log in to your application. But during development, you are not sure if the client wants to register in the database, files or event log.
So, you want to use DI to defer this choice to that which can be configured by the client.
This is some pseudo code (roughly based on Unity):
You create a logging interface:
public interface ILog { void Log(string text); }
then use this interface in your classes
public class SomeClass { [Dependency] public ILog Log {get;set;} }
introduce these dependencies at runtime
public class SomeClassFactory { public SomeClass Create() { var result = new SomeClass(); DependencyInjector.Inject(result); return result; } }
and the instance is configured in app.config:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name ="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity> <typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /> </typeAliases> <containers> <container> <types> <type type="MyAssembly.ILog,MyAssembly" mapTo="MyImplementations.SqlLog, MyImplementations"> <lifetime type="singleton"/> </type> </types> </container> </containers> </unity> </configuration>
Now, if you want to change the registrar type, just go to the configuration and specify a different type.
Will Apr 13 '09 at 14:19 2009-04-13 14:19
source share