Dependency injection with a static logger, static helper class

前端 未结 4 760
[愿得一人]
[愿得一人] 2020-11-30 04:10

I have a static class which calls a static Logger class,

e.g

static class DoesStuffStatic
{
  public static void DoStuff()
  {
    try
    {
      //         


        
4条回答
  •  星月不相逢
    2020-11-30 04:36

    This is a very simple way to "inject" the functionality of a static logger.

    public static class Logger
    {
        private static Action _logError;
        public static bool Initialised;
    
        public static void InitLogger(Action logError)
        {
            if(logError == null) return;
            _logError = logError
            Initialised = true;
        }
    
        public static void LogError(string msg, Exception e = null)
        {
            if (_logError != null)
            {
                try
                {
                    _logError.Invoke(msg, e);
                }
                catch (Exception){}
            }
            else
            {
                Debug.WriteLine($"LogError() Msg: {msg} Exception: {e}");
            }
        }
    }
    
    public class MainViewModel
    {
        public MainViewModel()
        {
            //Inject the logger so we can call it globally from anywhere in the project
            Logger.InitLogger(LogError);
        }
        public void LogError(string msg, Exception e = null)
        {
            //Implementation of logger
        }
    }
    

提交回复
热议问题