Domanda

I have a .NET assembly that wraps an XML configuration file. The config file contains a number of system settings including the path and file name formatting info for the error log file. Other assemblies reference this one through a singleton class:

public sealed class SettingsManager
{
    private static volatile SettingsManager manager;
    private static object syncRoot = new Object();

    //...

    private SettingsManager()
    {
        //load XML config file
    }

    public static SettingsManager Manager
    {
        get
        {
            if (manager == null)
            {
                lock (syncRoot)
                {
                    if (manager == null)
                        manager = new SettingsManager();
                }
            }
            return manager;
        }
    }

    //......
    //Methods getting and setting configuration data
    //......
}

I also have a Logging assembly that provides classes for error handling and usage tracking in the rest of the system. It references the Settings library to figure out where to save errors to:

SettingsManager.Manager.GetCurrentErrorFileName();

So the Settings assembly is a core dependency for the other assemblies in the project. But if I need to log errors in the Settings library I can't very well include the Logging assembly as a reference for Settings because I'll have a circular reference.

The problem I'm bumping into, is how do I handle errors that may be generated by the XML file routines in the Settings library? Do I hard-code a default file location for these errors to write to? What is best practice in this case?

I thought about the system event log, but these assemblies are going to be used in both a Windows service and a hosted MVC website. So I don't think the event log is an option.

È stato utile?

Soluzione

Two words... dependency injection.

More likely than not, your Logging assembly has absolutely no business knowing about the Settings assembly. It should probably either:

  1. Expect some environment variable to be set in the app domain telling it where to log, with a sensible default if not provided
  2. Expect something to tell it where to log (perhaps by setting a property on the logger)

In either option, the entry-point to your app is a good place to do this. Maybe in your first few lines of code you'd do something like:

Logger.LogFilePath = Settings.Manager.GetCurrentErrorFileName();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top