Collections repository implementation with the ability to handle serialization
I have several collections that all look the same but operate on different types of collection items, like this:
[CollectionDataContra开发者_如何学运维ct(ItemName = "Culture")]
public sealed class Cultures : List<LangCult>
{
}
The important piece of code here is the CollectionDataContract
attribute which allows us to serialize this collection into an XML file with DataContractSerializer
. The entire collection is serialized into one XML file named as the name of the type of collection class, for instance Cultures.xml
I would like to come up with a repository, precisely with an interface for a repository, that would work on all of the possible collections, for instance public class Slugs : List<string>
.
I tried something like this, but I don't know whether it's the best option:
public interface ICollectionsRepository<T> where T : IEnumerable
Your thoughts?
Please do not respond with instructions on how to serialize because that is not the issue here and I have it working.
Maybe I should've said I wanted an interface for generic collection with generic items where items have a common base class. This is how I solved it and hopefully someone one day finds it useful.
/// <summary>
/// This repo enables us to work with serialisable collections. Collection class has
/// to inherit from IEnumerable and must be described with CollectionDataContract attribute
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ICollectionsRepository<T, V> where T : Collection<V>
{
/// <summary>
/// Get collection from datastore
/// </summary>
/// <returns>List of items</returns>
T Load();
/// <summary>
/// Add new collection item to datastore
/// </summary>
/// <param name="item">Item to be added to the collection</param>
void Add(V item);
}
public class XmlCollectionsProvider<T, V> : ICollectionsRepository<T, V> where T: Collection<V>, new() where V: CollectionItem
{
private readonly string _file = Path.Combine(XmlProvider.DataStorePhysicalPath, typeof(T).Name + ".xml");
public T Load()
{
if (!DefaultsExist()) {
CreateDefaults();
}
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
T obj = null;
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(new FileStream(_file, FileMode.Open, FileAccess.Read),
new XmlDictionaryReaderQuotas());
obj = (T)dcs.ReadObject(reader, true);
reader.Close();
return obj;
}
public void Add(V item)
{
T collection = Load();
collection.Add(item);
Save(collection);
}
}
[CollectionDataContract(ItemName = "Culture")]
public sealed class Cultures : List<LangCult> { }
[DataContract]
public class LangCult : CollectionItem
{
...
}
[DataContract]
public abstract class CollectionItem
{
[DataMember]
public string Id
{
get;
set;
}
}
精彩评论