2

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

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.

i got a similar code which implement the above issue with DI patter. here is the code

public interface ILog
{
  void Log(string text);
}

then use this interface in your classes

public class SomeClass
{
  [Dependency]
  public ILog Log {get;set;}
}

inject those 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>

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.

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

4
  • 1
    don't do registering in xml. Just a good advice Jan 10, 2013 at 14:14
  • I only have experiance with MEF but there you have the option to import several dependencies of a contract as [ImportMany]. Also no need to register the dependencies. Just mark the classes with [Export]
    – Moriya
    Jan 10, 2013 at 14:17
  • 1
    @IlyaIvanov It'd be better advice if you mentioned why so something can be learned out of it.
    – C.Evenhuis
    Jan 10, 2013 at 14:27
  • @C.Evenhuis I've tried to figure out what was posted in question and didn't had time for reasonable argument against xml-based registering. Sorry about that, I will try to expand my response Jan 10, 2013 at 14:32

2 Answers 2

3

The reason a DI framework is useful is to avoid needing to make a lot of boilerplate factory implementations, like this:

public class SomeFactory
{
    public SomeClass GetSomeClass()
    {
          return new SomeClass(new SomeDep1(), new SomeDep2(new SomeInnerDep()));
    }
}

If you don't have a simple need in a factory, don't shy away from just writing what you need. In your example:

public class ILogFactory
{
  public ILog Create(CountryCode code)
  {
     if(code == CountryCode.GBR) return new EvenLogger();

     if(code == CountryCode.UK) return new DatabaseLogger(_providerFactory());

     ///etc...
  }
}

EDIT: Notice also that I wrote an ILog factory instead of a SomeClassFactory. That way users of the factory couple to an interface, rather than a concrete instance. This is a really helpful practice in DI and generally, as it allows you to substitute desired concrete types.

2
  • due to the lack of knowledge of advance progrraming like DI and any Di container....i just do not understand what u try to do.if i follow ur code then why create() function return instance of ILog?? would u like to write a complete code as a result ur objective will be clear to me....thanks :)
    – Thomas
    Jan 10, 2013 at 18:42
  • from ur code it looks it is not DI...rather something different.
    – Thomas
    Jan 11, 2013 at 15:13
2

You have to do two things: 1) Register two mappings with specific names in your unity container. Modify your xml config like this:

<type type="MyAssembly.ILog,MyAssembly"
            mapTo="MyImplementations.SqlLog, MyImplementations"
            name="sql">
        <lifetime type="singleton"/>
      </type>
<type type="MyAssembly.ILog,MyAssembly"
            mapTo="MyImplementations.FileLog, MyImplementations"
            name="file">
        <lifetime type="singleton"/>
      </type>

(notice the "name" attribute on the "type" element)

And then resolve your dependency like that (sorry I don't know DependencyInjector class so I use Unity container (Microsoft.Practices.Unity.IUnityContainer):

// create and initialize unity container once somewhere in startup code.
var сontainer = new UnityContainer();
container.LoadConfiguration(); // load unity configuration from application xml config 

// then use container to resolve dependencies.
if (CountryCodeSaysToUseDb())
   return container.Resolve<MyAssembly.ILog>("sql");
if (ContryCodeSaysToUseFile())
   return container.Resolve<MyAssembly.ILog>("file");

But be careful, because by explicitly choosing specific implementation inside your own code you are breaking DI pattern.

3
  • can u plzz tell me what will be my two Assembly name one for DB and another for flat file. here u every time come with same name called "MyAssembly.ILog" what is MyAssembly.ILog ?? i am not familiar with any DI container.so details discuss would be great help for me like newbie...:)
    – Thomas
    Jan 10, 2013 at 18:38
  • MyAssembly.ILog is just a type name (with namespace) taken from your code sample. It is used as a generic parameter in the Resolve method to say: "Give me an implementation (mapping) for this type (ILog) named "sql" (or "file").
    – vlad2135
    Jan 11, 2013 at 7:06
  • so u means to say when i will create class library then every time i have to give a name to root namespace "MyAssembly.ILog" but project name would be different. can u plzz tell me what will be my many class library project name and their root name space.
    – Thomas
    Jan 11, 2013 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.