【发布时间】:2013-10-08 16:57:00
【问题描述】:
我有这样的课:
public class MyClass
{
public MyClass()
{
this.Dependency = new Dependency(this);
}
}
我想将new Dependency() 调用移至构造函数。
public class MyClass
{
public MyClass(IDependency dependency)
{
this.Dependency = dependency;
}
}
我不知道如何绑定它,以便使用 'this' 构造函数参数创建 IDependency。
Bind<IDependency>()
.To<Dependency>()
.WithConstructorArgument("myClass", ctx => ctx.???); // How do I do this?
【问题讨论】:
-
你不能传递'this',因为在创建参数时'this'不存在。您只能在手动情况下摆脱它,因为您在构造函数本身内部创建它,此时已经创建了“this”。一般来说,这种循环引用是一种“代码味道”(至少当 Dependency 是公共类时),因此您可能需要考虑是否可以重构它,以便 MyClass 和 Dependency 都依赖于具有必要的共享功能。
-
你有没有为此找到解决方案?
-
并非如此。我正在重构一个现有的大型项目,并且一次解决一个问题。但我还不清楚这个最好的方法。一个更现实的例子是
Contact,它有一个ContactAddress依赖项(当前在构造函数中实例化),但地址有依赖项,所以我想解决它。我可以移动ContactAddress以使用属性注入而不是构造函数注入,但我仍然不清楚要使用的绑定。