Skip to content

Commit

Permalink
Merge pull request #646 from Styxxy/memleakxml
Browse files Browse the repository at this point in the history
fixes #643 add xmlserializer cache
  • Loading branch information
Oren Novotny authored Apr 8, 2019
2 parents 564559d + 8fef9a0 commit 16d5a71
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions Refit/XmlContentSerializer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Http;
using System.Text;
Expand All @@ -12,6 +13,7 @@ namespace Refit
public class XmlContentSerializer : IContentSerializer
{
private readonly XmlContentSerializerSettings settings;
private readonly ConcurrentDictionary<Type, XmlSerializer> serializerCache = new ConcurrentDictionary<Type, XmlSerializer>();

public XmlContentSerializer() : this(new XmlContentSerializerSettings())
{
Expand All @@ -24,8 +26,8 @@ public XmlContentSerializer(XmlContentSerializerSettings settings)

public Task<HttpContent> SerializeAsync<T>(T item)
{
var xmlSerializer = new XmlSerializer(item.GetType(), settings.XmlAttributeOverrides);

var xmlSerializer = serializerCache.GetOrAdd(item.GetType(), t => new XmlSerializer(t, settings.XmlAttributeOverrides));
using (var stream = new MemoryStream())
{
using (var writer = XmlWriter.Create(stream, settings.XmlReaderWriterSettings.WriterSettings))
Expand All @@ -41,8 +43,8 @@ public Task<HttpContent> SerializeAsync<T>(T item)

public async Task<T> DeserializeAsync<T>(HttpContent content)
{
var xmlSerializer = new XmlSerializer(typeof(T), settings.XmlAttributeOverrides);

var xmlSerializer = serializerCache.GetOrAdd(typeof(T), t => new XmlSerializer(t, settings.XmlAttributeOverrides));
using (var input = new StringReader(await content.ReadAsStringAsync().ConfigureAwait(false)))
using (var reader = XmlReader.Create(input, settings.XmlReaderWriterSettings.ReaderSettings))
return (T)xmlSerializer.Deserialize(reader);
Expand Down

0 comments on commit 16d5a71

Please sign in to comment.