After lots of research and trial an error. I finally figure out where my memory leak was coming from. You need to use XmlSerializer as a static object.
Memory Leak using StreamReader and XmlSerializer
private string Serialize(Bob request)
{
XmlSerializer xSer = CreateOverrider(request.Token.Value.Trim().Length < 1 ? true : false);
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.schema.com/schema");
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
xSer.Serialize(writer, request, xmlnsEmpty);
}
return sb.ToString();
}
// https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore(v=vs.110).aspx
private XmlSerializer CreateOverrider(bool override)
{
// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs = new XmlAttributes();
attrs.XmlIgnore = override;
attrs.XmlElements.Add(new XmlElementAttribute("validation"));
xOver.Add(typeof(RegisterBobRequest), "validation", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(BobRequest), xOver);
return xSer;
}
That code above resulted in a slow memory leak, and on windows was not an issue. Once published to Ubuntu 16.04 on .net core 2.0 the memory would increase by 1meg every minute or so. The end result was to make the "XmlSerializer" static and readonly.
private static readonly XmlSerializer xmlSerializer = CreateOverrider(false);
private static readonly XmlSerializer xmlSerializerTrue = CreateOverrider(true);
private string Serialize(Bob request)
{
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.schema.com/schema");
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
if (request.Token.Value.Trim().Length < 1)
{
xmlSerializerTrue.Serialize(writer, request, xmlnsEmpty);
}
else
{
xmlSerializer.Serialize(writer, request, xmlnsEmpty);
}
}
return sb.ToString();
}
At the end of the day when the memory leak the server would run up to the 8gig limit and need to have the service recycled. After this update the process has been running at ~330meg without issue.
We push around 100k requests through this service daily now with out issue. I hope this helps someone else.