Circular Reference with Mongo Appender can Crash Your Process

jieforest發表於2012-06-11
I’ve blogged some days ago on the possibility to save log4net logs inside a Mongo database, but you should be aware that this technique can be dangerous if your objects have circular references.

Acircular reference happens when object A reference object B and object B directly or indirectly reference object A again and this is a high risk when you work with Mongo Serializer.

Mongo Serializer does not likes circular references (it is perfectly acceptable, because documents with circular references cannot be saved into a document database), but the problem is: if you try to serialize an object that has a circular reference you will get a StackOverflowException and your process will crash, as stated in official documentation from MSDN.

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow.

If you remember how I modified MongoDb log4net appender, I decided to save into MongoDB complex objects with this code:

CODE:

if (compositeProperties != null && compositeProperties.Count > 0)
{
    var properties = new BsonDocument();
    foreach (DictionaryEntry entry in compositeProperties)
    {
        BsonValue value;
        if (!BsonTypeMapper.TryMapToBsonValue(entry.Value, out value))
        {
            properties[entry.Key.ToString()] = entry.Value.ToBsonDocument();
        }
        else
        {
            properties[entry.Key.ToString()] = value;
        }
    }
    toReturn["customproperties"] = properties;
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-732425/,如需轉載,請註明出處,否則將追究法律責任。

相關文章