2
我很難嘗試創建一個XmlRepository。這裏的問題我有唯一的選擇使用XmlSerializer來做到這一點。如何使用XmlSerializer創建XmlRepository?
請檢查出來。這真讓我的代碼亂成一團,令人沮喪。我想知道我該如何改進這些代碼,我正在考慮創建一個單例,但我不知道如何繼續。
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;
}
}
}
有任何疑問,請讓我知道。 非常感謝