Cannot access a disposed object sometimes when logging

Topics: Logging Application Block
May 15, 2013 at 4:15 PM
I've upgraded to EntLib 6 and I get this error when using the logging block to log to a database: "Cannot access a disposed object".

Here is my code:
public void Write(string message, TraceEventType traceEventType)
        {
            DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.SetLogWriter(new LogWriterFactory().Create(), false);

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(message, "General", 1, 1, traceEventType, "That Webstore");
        }
Here is the stack trace:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter'.
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.get_SyncLock()
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.ExecuteReadOperation(Action readOperation)
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.Write(LogEntry log)
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.Write(Object message, IEnumerable`1 categories, Int32 priority, Int32 eventId, TraceEventType severity, String title, IDictionary`2 properties)
Any ideas? This doesn't happen all the time, just sometimes.
May 15, 2013 at 5:50 PM
Edited May 15, 2013 at 5:50 PM
Are you using multi-threading or is this a web app (which could have multiple concurrent requests)? When you call SetLogWriter it disposes of the current writer which could cause any currently executing Write calls to throw an ObjectDisposedException.

I would recommend to modify the code to only perform the following once:
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);

Microsoft.Practices.EnterpriseLibrary.Logging.Logger.SetLogWriter(new LogWriterFactory().Create(), false);
These two lines are only required to run once to initialize the blocks. So, you could move them to Application_Start or perhaps perform some lazy initialization if you have your own Logger class.

This should hopefully resolve your issue and improve performance.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to