Registration structure is injected into classes

Should the registration framework be implemented in the classes that they need, or should each class that needs it just know the structure and use it directly? I am using Log4Net, and I am currently introducing a service that wraps this structure in classes that should be able to register, knowing that logging is likely to not change and that most of the pieces it needs are introducing an answer in that sense?

+5
source share
6 answers

Injection is more flexible in the long run, as you can easily selectively enter in certain places and selectively disable logging, etc.

+3

, , . , .

+2

, AOP, . PostSharp. , . IL- . PostSharp , . plugin log4net .

EDIT: , .

+1

, , . , , .

CommonLogging (. fooobar.com/questions/1032254/... , Common.Logging), : factory (LoggerManager), .

+1

(, Spring.NET), , . , , /, , , , . , (CommonLogging, , log4net, Enterprise Library).

, , . , . APOP Injection - , AOP . , , , AOP (YMMV, ).

0

CSharpAtl,

, Log4net? . / wiki .

DI/Log4net .

, , , "logger", - :

public class Foo
{
  private ILogger logger;

  public Foo(ILogger logger) //Injection via constructor
  {
    //Which "named" logger is this anyway?  Is it Foo's?  If so, how is it Foo's?
    this.logger = logger;
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

- Log4net ( NLog , , ), :

public class Foo
{
  private static ILogger logger = 
          LogManager.GetLogger(
              System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

  public Foo()
  {
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

, , Foo, , ? , , . , (, "DatabaseAccess", "AppStartup", "AppShutdown" ..), .

"Logger" ( ) "LogManager" ( Log4net LogManager), - ? DI " " ? , Unity - , .

, "LogManager" :

public class Foo
{
  private static ILogger logger;

  public Foo(ILogManager logManager) //Injection via constructor
  {
    logger = logManager.GetLogger
                    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    //Since logger is (should it be?) static, maybe should be like this:

    if (logger = null)
    {
      logManager.GetLogger
                 (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

, - ILogManager ( Log4net LogManager) , ILogger, - , DI , ILogger .

DI .NET( , # .NET ). - VB6 + V++ 6.

...

...

SO , AutoFac, , DI. , , - , -, , this, ( ). , , , , AutoFac, (, Log4Net NLog).

...

0

All Articles