我们在MVC3项目中使用spring作为我们的IOC容器。我正在尝试创建一个基本控制器,它将对我们的IUserIdentity接口具有构造函数依赖性。我想在抽象类的应用程序上下文文件中定义一次构造函数依赖项,并希望spring能够为每个派生类注入该函数。
public abstract class ControllerBase : Controller
{
private readonly IUserIdentity _userContext;
public ControllerBase(IUserIdentity userContext)
{
_userContext = userContext;
}
}
public class ChildController : ControllerBase
{
private readonly IChildDependency _childService;
public ChildController(IUserIdentity userContext, IChildDependency childService)
: base(userContext)
{
_childService= childService;
}
}
我希望有一种方法可以定义类似下面的内容 - (不确定它是如何工作的),而无需为每个派生类重新定义UserIdentity。
<object id="ControllerBase" abstract="true" singleton="false" >
<constructor-arg index="0">
<ref object="DefaultUserIdentity"/>
</constructor-arg>
</object>
<object id="ChildController" singleton="false" >
<constructor-arg index="1" >
<ref object="ConcreteChildDependency" />
</constructor-arg>
</object>
正如所料,当我做这样的事情时,spring不知道在派生(ChildController)类中为第一个参数放入什么。
答案 0 :(得分:3)
尝试使用ControllerBase
属性参考parent
对象定义:
<object id="ControllerBase" abstract="true" singleton="false" >
<constructor-arg index="0">
<ref object="DefaultUserIdentity"/>
</constructor-arg>
</object>
<object id="ChildController" singleton="false" parent="ControllerBase" >
<constructor-arg index="1" >
<ref object="ConcreteChildDependency" />
</constructor-arg>
</object>
这将允许ChildController
“继承”ControllerBase
中的对象定义。有关object definition inheritance的更多信息,请参阅spring.net文档。您可能希望从构造函数args,btw中删除索引属性。如果可以隐式解析构造函数参数类型,则不需要它们。当然,您的ChildController
需要一个类型定义。