将事物分离出来的想法是正确的,将内容解析从模型中分离出来似乎是正确的。
我有时会使用助手来完成工作。如果您希望使其更具可测试性并保持模型清洁(尤其是模型是实体框架模型的情况),那么可能会使用类似于下面显示的方法。
/// <summary>
/// Interface for file handling
/// </summary>
public interface IFileParser
{
void Parse();
}
/// <summary>
/// An interface for the model you wish to work on
/// Will allow DI and Mocking in Unit Tests
/// </summary>
public interface IMyModel
{
string Content { get; set; }
}
/// <summary>
/// The model that has the content you are going to work with
/// </summary>
public class MyModel : IMyModel
{
string Content { get; set; }
// other properties
}
/// <summary>
/// The class to handle the model.
/// </summary>
public class FileHandler : IFileParser
{
private IMyModel _model;
public FileHandler(IMyModel model)
{
_model = model;
}
public void Parse()
{
string contentToHandle = _model.Content;
//Do stuff here to ensure all is good.
//NOTE: you could change the interface to return an ID to work with
}
}
然后你可以像这样处理解析:
FileHandler handler = new FileHandler(thisModel);
handler.Parse();
不过,这可能有点矫枉过正。取决于你在做什么:)