【发布时间】:2011-04-07 14:38:31
【问题描述】:
我有一个类可以协调数据文件包的准备、验证和清理例程。我正在努力寻找一种在使用 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
}
}
如您所见,作为流程的一部分,我需要动态解析验证类。在过去,我会创建一个工厂类来定位正确的验证器并返回它。我倾向于通过构造函数注入该工厂,但想把它放在那里看看是否有更好的方法来处理嵌套依赖解析,而无需传递 IoC 容器引用。
(可能有a duplicate question,但如果我们问的是同样的问题,我仍在努力解决)
【问题讨论】:
-
注入抽象工厂是要走的路:stackoverflow.com/questions/1943576/…
标签: design-patterns dependency-injection ioc-container ninject