使用Castle Windsor ISubDependencyResolver获取参数名称时遇到一些问题。 我有类似下面的代码,在Foo的情况下,我希望myBar.BarName为“Foo_myBar”
Public Class Foo
{
private readonly IBar myBar;
Public Foo(IBar myBar){
this.myBar = myBar;
}
}
Public Class Bar: IBar
{
Public string BarName {get; private set;}
Public Bar(string barName){
BarName = barName;
}
}
public class BarNameResolver : ISubDependencyResolver
{
public bool CanResolve(CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
return context.RequestedType == typeof (IBar)
&& dependency.TargetType == typeof (string)
&& dependency.DependencyKey.Equals("barName");
}
public object Resolve(CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
return string.Format("{0}_{1}",
context.Handler.ComponentModel.Name,
**NameOfFooBarParameter**);
}
}
是否有办法在ISubDependencyResolver中获取“myBar”?
我需要这个在Foo中有多个具有不同配置的IBar实例。
答案 0 :(得分:1)
由于BarNameResolver是一个subdepedency解决方案,因此很容易混淆组件和依赖
public bool CanResolve(
CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
return context.RequestedType == typeof(Foo)
&& dependency.TargetType == typeof(IBar);
}
public object Resolve(
CreationContext context,
ISubDependencyResolver contextHandlerResolver,
ComponentModel model,
DependencyModel dependency)
{
var myBar = dependency.DependencyKey;
return null;
}
在您的示例中,变量myBar现在将包含字符串“myBar”。您可以使用它来解决依赖关系。