I’m having a hard time trying to create a XmlRepository. The problem here I have the only choice to do this using XmlSerializer.
Please, check it out. It really a mess my code and frustrating. I wanna know how can I improve this code, I was thinking in creating a singleton but I’m not sure how to continue.
public interface IRepository<T>
where T : class
{
T GetById(object id);
IEnumerable<T> All();
void Insert(T entity);
void Remove(T entity);
void SaveChanges();
}
public class XmlRepository : IRepository<Configuration>
{
public XmlRepository(string filename)
{
FileName = filename;
}
public XmlRepository(string filename)
{
FileName = filename;
}
internal string FileName { get; private set; }
private Configuration GetById(object id)
{
throw new NotImplementedException();
}
public IEnumerable<Configuration> All()
{
return Get();
}
public void Insert(Configuration entity)
{
var configurations = Get();
configurations.Add(entity);
Save(configurations);
}
public void Remove(Configuration entity)
{
var configurations = Get();
configurations.Remove(entity);
Save(configurations);
}
private List<Configuration> Get()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>), null, new Type[] { typeof(BinaryConfiguration) }, new XmlRootAttribute("Configurations"), "http://ofimbres.wordpress.com/");
StreamReader myWriter = new StreamReader(FileName);
var list = serializer.Deserialize(myWriter);
myWriter.Close();
return (List<Configuration>)list;
}
catch (InvalidOperationException ex)
{
throw ex;
}
}
public void Save(object configurations)
{
try
{
XmlSerializer serializer = new XmlSerializer(configurations.GetType(), null, new Type[] { typeof(BinaryConfiguration) }, new XmlRootAttribute("Configurations"), "http://ofimbres.wordpress.com/");
StreamWriter myWriter = new StreamWriter(FileName);
serializer.Serialize(myWriter, configurations);
myWriter.Close();
}
catch (XmlException ex)
{
throw ex;
}
}
}
Any doubt, please let me know.
Thanks a lot
Instead of reading and writing the file every time you call the repository, I would do the following:
In the constructor you read the file into a list of
Configurationobjects. Just like you do in theGetmethod at the moment. You save this list in a field of the class and use it for all the other methods (add, etc.).Your repository does have a
SaveChangesmethod, so this is the ideal place to serialize the configuration back to disk.This should be a lot more performant than the current approach, less complex and therefore also less error-prone.
Edit: Here is a start:
Also some general suggestions
usingfor handling files/streams and other resources which needs to be disposed (StreamReaderandStreamWriterin this case). This guarantees that the file will be closed even when there is an exception.throwinstead ofthrow exto preserve the full stack trace.Hope this helps!