【发布时间】:2013-01-27 18:39:44
【问题描述】:
我希望参数实现优于默认注册的实现,但它不起作用。
不正确的偏好演示
private static void Main(string[] args)
{
PassParamThatsAlreadyRegisteredAtResolutionTime();
Console.ReadLine();
}
private static void PassParamThatsAlreadyRegisteredAtResolutionTime()
{
Console.WriteLine("Passing argument that is already registered
does not take precedence over the default implementation");
var container = new WindsorContainer();
container.Register(
Component.For<ISimpletonManager>()
.ImplementedBy<SimpletonManager>()
.LifestyleTransient()
.Properties(PropertyFilter.IgnoreAll));
container.Register(Component.For<ISimpleton>().UsingFactoryMethod(() =>
new Simpleton("Default Implementation"))
.LifestyleTransient());
// The above line could equally be the following, result is the same:
// container.Register(Component.For<ISimpleton>()
// .ImplementedBy<Simpleton>().LifestyleTransient());
var runtimeConstructorParam = new Simpleton("Passed In Implementation");
var runtimeArguments = new Arguments(
new object[] {runtimeConstructorParam});
var shouldBeManagerWithPassedInSimpleton = container
.Resolve<ISimpletonManager>(runtimeArguments);
Console.WriteLine(shouldBeManagerWithPassedInSimpleton.Log);
}
控制台输出
Passing argument that is already registered
does not take precedence over the default implementation
Birth With Child Simpleton: Default Implementation
如何反转偏好?
- 我需要能够忽略默认注册的依赖项,而是使用提供的参数作为 ISimpleton 依赖项进行 Castle Windsor 解析吗?
- 我是否需要实现自己的IDependencyResolver?怎么样?
- 或者DynamicParameters在这里有用吗?
提供的依赖 - Simpleton 类
public class Simpleton : ISimpleton
{
public Simpleton(string id)
{
Id = id;
}
public string Id { get; set; }
}
已解析类型 - SimpletonManager
public class SimpletonManager : ISimpletonManager
{
private ISimpleton _child;
public SimpletonManager(ISimpleton simpleton)
{
Child = simpleton;
}
public ISimpleton Child
{
get { return _child; }
set
{
_child = value;
Log = "Birth With Child Simpleton: " + Child.Id;
}
}
public string Log { get; private set; }
}
[Using Castle.Core.dll and Castle.Windsor.dll 3.1.0 (2012-08-05)]
【问题讨论】:
-
您正在传递一个对象数组,而 Windsor 人似乎建议传递一个 IDictionary 或一个匿名对象 - 但不确定这是否有任何区别:docs.castleproject.org/Windsor.Passing-Arguments.ashx
-
@JoannaTurban Arguments 类实际上是来自 Windsor 库和 creating it with an object array is what you find in the documentation 的专用字典 - 不管怎样,如果使用非泛型参数,完全相同的代码也可以工作......谢谢你的想法。跨度>
标签: c# .net dependency-injection castle-windsor constructor-injection