How to inject dependency for Logger?

May 27, 2010 at 8:00 AM

Hi All,

1. How to inject dependency for the Logger class and I should not use Constructor DI?

2. Logger  is used frequently in the application.

3. Below is the code snippet:

Logger's implementation is:  

 using EL = Microsoft.Practices.EnterpriseLibrary.Logging;

  public class Logger : ILogger
    {
        #region ILogger Members

         public void Log(LogEntry entry)
        {
            var elEntry = new EL.LogEntry();
            elEntry.ActivityId = entry.CorrelationId;
            EL.Logger.Write(elEntry);
        }

  }

I have a static class like:

public static class StaticFactory

 {

 public delegate T GetInstance<T>();

 public  static GetInstance<ILogger> Logger;

 }

On startup event of the application, the below statements will be executed,

// These statements are under same class

this.container.RegisterType<ILogger, Logger>();

StaticFactory.Logger = () => this.container.Resolve<ILogger>();

Below statement will resolve the dependency.

ILogger logger  =   StaticFactory.Logger(); // <-- this statement is under different class

But exposing delegates to outside world is not advisable. And I should not use Constructor DI.

So is there any way to handle this?

Thanks in advance,

Manju