gpt4 book ai didi

c# - 结构图 - 构造函数中的依赖集合

转载 作者:行者123 更新时间:2023-11-30 15:24:51 27 4
gpt4 key购买 nike

我的注册表中有以下代码:

        Scan(x =>
{
x.Assembly(Assembly.GetExecutingAssembly());
x.AddAllTypesOf<IXmlExtractor>();
});

此代码将我的程序集中的所有 IXmlExtractor 实例添加到 IoC 容器中。

现在我想在我的类中使用所有找到的实例,但我更喜欢通过构造函数注入(inject)而不是在方法中使用 ObjectFactory。希望下面的代码说明了我想做什么:

class Engine : IEngine
{
private readonly ILog _logger;
private readonly ICurveConfigRepository _configRepo;
private readonly IDataExtractor _dataExtractor;

public Engine(ILog logger,
ICurveConfigRepository configRepo,
IDataExtractor dataExtractor
/* SomeCollectionOfIXmlExtractors allExtractors */)
{
_logger = logger;
_configRepo = configRepo;
_dataExtractor = dataExtractor;
}

public void Run(string mode)
{
_logger.Info(string.Format("About to run retrieve config for '{0}' mode.", mode));

var config = _configRepo.LoadConfig(mode);

_logger.Info("Config retrieved, extracting data");
var data = _dataExtractor.GetCurves(config);

_logger.Info("Data extracted");

// Foreach IXmlExtractor instance, call .DoStuff(data) with it.
// I don't like using ObjectFactory here - see comment in constructor
var extractors = ObjectFactory.GetAllInstances<IXmlExtractor>();

}
}

希望这很清楚,如果需要进一步解释,请回复。

  • C#:4.0
  • 结构图:2.5.4.0

谢谢,

格雷姆

最佳答案

您已经正确地向容器注册了所有实例。

Scan(x =>
{
x.Assembly(Assembly.GetExecutingAssembly());
x.AddAllTypesOf<IXmlExtractor>();
});

您需要做的就是声明一个数组变量,StructureMap 将自动处理构造函数注入(inject)。

class Engine : IEngine
{
private readonly ILog _logger;
private readonly ICurveConfigRepository _configRepo;
private readonly IDataExtractor _dataExtractor;
private readonly IXmlExtractors[] _allExtractors;

public Engine(ILog logger,
ICurveConfigRepository configRepo,
IDataExtractor dataExtractor
IXmlExtractors[] allExtractors)
{
_logger = logger;
_configRepo = configRepo;
_dataExtractor = dataExtractor;
_allExtractors = allExtractors;
}

public void Run(string mode)
{
_logger.Info(string.Format("About to run retrieve config for '{0}' mode.", mode));

var config = _configRepo.LoadConfig(mode);

_logger.Info("Config retrieved, extracting data");
var data = _dataExtractor.GetCurves(config);

_logger.Info("Data extracted");

// Use extractors...
foreach (var extractor in _allExtractors)
{
extractor.DoStuff(data);
}
}
}

关于c# - 结构图 - 构造函数中的依赖集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com