我有一个 CaSTLe Windsor 容器注册类如下...
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<IConfigProvider>()
.ImplementedBy<ConfigProvider>()
.LifeStyle.Singleton);
container.Register(Component.For<IDbRepository>()
.ImplementedBy<DbRepository>()
.LifeStyle.Singleton
.DependsOn(Dependency.OnValue(
"connectionString",
// -- Somehow call GetConfig() on the IConfigProvider --
)));
}
}
DbRepository 需要在对象构造时传入一个连接字符串。但是,该连接字符串实际上是由 IConfigProvider 提供的。
此时是否可以让温莎城堡以某种方式解析 IConfigProvider 并调用 GetConfig 方法?
如果这不是一个好主意,请考虑其他选项。
最佳答案
你可以使用 DynamicParameters
要做到这一点:
container.Register(Component.For<IDbRepository>()
.ImplementedBy<DbRepository>()
.LifeStyle.Singleton
.DynamicParameters((k,d) =>
{
var configProvider = k.Resolve<IConfigProvider>();
d["connectionString"] = configProvider.GetConfig();
}
)));
来自文档:
DynamicParameters works with a delegate which is invoked at the very beginning of component resolution pipeline.
换句话说,您将在解析组件之前检索连接字符串。
关于c# - 使用 CaSTLe 容器中的已注册组件为另一个组件提供依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30916792/