【问题标题】:Pattern for Resolving Nested Dependencies at Run-Time using an IoC Container使用 IoC 容器在运行时解决嵌套依赖关系的模式
【发布时间】: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,但如果我们问的是同样的问题,我仍在努力解决)

【问题讨论】:

标签: design-patterns dependency-injection ioc-container ninject


【解决方案1】:

假设验证器和处理器是可重用的,我会采取完全不同的方法。我会在构造函数中注入所有 RecordValidators 并向它们添加一个 CanHandle(??? packageFile) 方法,然后在循环中选择匹配的方法,或者注入一个具有所有验证器的验证器选择器并从中获取它。

【讨论】:

  • 那么这将需要向每个 RecordValidator 添加一个 CanHandle(string file) 方法,修改构造函数以接受 IEnumerable 并使用 Kernel.GetAll() 将它们全部注入?
  • 是的,但您不应该使用 GetAll 手动注入。将其留给 Ninject,它将在创建 PackageProcessor 实例时自动注入所有 RecordValidators。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2015-11-13
  • 2019-04-27
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多