Dependency Injection in .NET with examples c#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
i need help regarding DI but i never work with DI before.so concept is new for me.my issue is suppose i need to save log to database or flat file or may be windows event log. based on few parameter i want to save log data to DB or flat file or event log<br/>
<br/>
say for example if country code is GBR then event log will be saved to DB. if country code is USA then event log will be saved to flat file. if country code is USA then event log will be saved to windows event log.<br/>
<br/>
i got a similar code which implement the above issue with DI patter. here is the code<br/>
<br/>
public interface ILog<br/>
{<br/>
void Log(string text);<br/>
}<br/>
<br/>
then use this interface in your classes<br/>
<br/>
public class SomeClass<br/>
{<br/>
[Dependency]<br/>
public ILog Log {get;set;}<br/>
}<br/>
<br/>
inject those dependencies at runtime<br/>
<br/>
public class SomeClassFactory<br/>
{<br/>
public SomeClass Create()<br/>
{<br/>
var result = new SomeClass();<br/>
DependencyInjector.Inject(result);<br/>
return result;<br/>
}<br/>
}<br/>
<br/>
and the instance is configured in app.config:<br/>
<br/>
<?xml version="1.0" encoding="utf-8"?><br/>
<configuration><br/>
<configSections><br/>
<section name ="unity"<br/>
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,<br/>
Microsoft.Practices.Unity.Configuration"/><br/>
</configSections><br/>
<unity><br/>
<typeAliases><br/>
<typeAlias alias="singleton"<br/>
type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /><br/>
</typeAliases><br/>
<containers><br/>
<container><br/>
<types><br/>
<type type="MyAssembly.ILog,MyAssembly"<br/>
mapTo="MyImplementations.SqlLog, MyImplementations <br/>
<lifetime type="singleton"/><br/>
</type><br/>
</types><br/>
</container><br/>
</containers><br/>
</unity><br/>
</configuration><br/>
<br/>
but the problem with this above code it will do only one thing at a time. if the assembly implementation is there for DB then it will save it to DB or if the assembly implementation is there for flat file then it will save it to flat file.<br/>
<br/>
but my requirement is same with bit difference like i want to save data based on country code. so what i need to change in code and config file as a result i can save data any where based on country code. please help me with code & concept. thanks<br/>
<br/>

View the full article
 
Back
Top