.net - 城堡温莎国际奥委会 : Passing constructor parameters to child components

标签 .net castle-windsor

以下代码仅用于演示目的。

假设我有 2 个组件(businessService 和 dataService)和一个 UI 类。

UI类需要一个业务服务,businessService需要一个dataService,dataService依赖一个connectionString。

形成我需要解析业务服务的 UI 类,所以我正在编写以下代码:

var service = container.Resolve<BusinessService>(new { dependancy = "con string 123" }));

请注意,dependancy 是 connectionString 构造函数参数。

但是上面的代码不起作用,说dataService期望的依赖没有得到满足。

Can't create component 'dataService' as it has dependencies to be satisfied. dataService is waiting for the following dependencies:

Keys (components with specific keys) - dependancy which was not registered.



因此,作为一种解决方法,我正在这样做:
var service = container.Resolve<BusinessService>(new { dataService = container.Resolve<IDataService>(new { dependancy = "123" }) });

但是从设计、编码风格和许多角度来看,这不是一个好方法。

因此,如果您能建议为什么它不能以简单的方式工作,或者您有更好的解决方法,请分享。

最佳答案

您看到的行为是设计使然。

有几种方法可以解决这个问题,具体取决于您要传递的值的动态程度。

The documentation做的很详细,所以我不会在这里重申。

更新

为了清楚起见 - Windsor 不会在解析管道中传递内联参数。原因很简单——这样做会破坏抽象。调用代码必须隐含地知道您的 BusinessService取决于 DataService这取决于连接字符串。

如果您绝对必须这样做,请务必明确说明。这就是你正在做的事情 - 解决 DataService显式依赖于连接字符串,并显式解析 BusinessService路过 DataService作为依赖。

为了使事情真正明确(并且更好用),我建议使用 Typed Factory 而不是直接调用容器

public interface IFactory
{
   IDataService ResolveDataService(string connectionString);
   IBussinessService ResolveBussinessService(IDataService dataService);
   // possibly release method for IBussinessService as well
}

关于.net - 城堡温莎国际奥委会 : Passing constructor parameters to child components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3904951/

相关文章:

c# - 插入具有一对多关系的新记录/更新现有记录

c# - XDocument 将制表符更改为空格

c# - 用 IoC (CaSTLe Windsor) 替换以下代码

caSTLe-windsor - Circular 'interfaces' 依赖项和 CaSTLe-Windsor

.net - 使用 Windows 身份验证从 Mono 调用 WCF 服务

.net - 如何检测系统时间是否更改? (来自.net)

c# - Akka.NET 和 MVVM

NHibernate - 在 Dispose() 方法中使用 Session.Flush() - 好主意吗?

c# - .NET 应用程序中的最大线程数?

winforms - MVP模式中使用Windsor caSTLe进行依赖注入(inject)的循环引用问题