我有一个类来协调数据文件包的准备,验证和清理例程。我正在努力寻找一种在使用IoC容器时感觉正确的模式(在本例中为Ninject)。我遇到的问题是,根据包中提供的内容,我可以使用几个验证类中的一个。以下是对正在发生的事情的粗略了解:
public class PackageProcessor
{
private readonly ILog log;
public PackageProcessor(ILog log)
{
this.log = log;
}
public void Process(CustomerProfile profile, PackageType type, string path, bool validateOnly = false, bool offlineValidation = false)
{
// ...
// Uncompress package files (if compressed) or copy raw files to woroking folder
// Ensure working folder contains the required files for the package type
// Validate package data
foreach (var packageFile in packageConfiguration)
{
var timer = Stopwatch.StartNew();
var recordCount = 0UL;
var validator = DependencyResolver.Kernel.Get<RecordValidator>(metadata =>
metadata.Has("file") &&
String.Equals(metadata.Get<string>("file"), packageFile.Name, StringComparison.OrdinalIgnoreCase));
using (var reader = new CsvReader(new StreamReader(Path.Combine(workingFolder.FullName, packageFile.Name)), false))
{
while (reader.ReadNextRecord())
{
var recordResult = validator.IsValid(reader);
if(!recordResult.IsValid)
{
// LOG: record error messages
// Mark the job as failed
}
recordCount++;
}
}
// LOG: File appears to be valid. {0} records were found.
// LOG: File contains invalid records. {0} records were found, {1} were invalid.
timer.Stop();
log.Info(m => m(Strings.RecordsProcessed, recordCount, timer.Elapsed, (recordCount / timer.Elapsed.TotalSeconds)));
}
// Clean and output the data
}
}
正如您所看到的,我需要在流程中动态解析验证类。在过去,我会创建一个Factory类来定位正确的验证器并将其返回。我倾向于通过构造函数注入该工厂,但是想把它放在那里,看看你是否有更好的方法可以处理嵌套的依赖解析,而不必传递IoC容器引用。
(可能有a duplicate question,但如果我们问同样的事情,我仍然会努力解决这个问题。
答案 0 :(得分:2)
假设验证器和处理器是可重用的,我会采取完全不同的方法。我将构造函数中的所有RecordValidators注入并向它们添加一个CanHandle(??? packageFile)方法并在循环中选择匹配的方法,或者选择具有所有验证器的验证器选择器并从中获取它。