3

我们在 MVC3 项目中为 IOC 容器使用 spring。我正在尝试制作一个基本控制器,它将对我们的 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) 类中为第一个参数输入什么。

4

1 回答 1

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有关对象定义继承的更多信息,请参阅 spring.net 文档。您可能希望从构造函数 args 中删除索引属性,顺便说一句。如果可以隐式解析构造函数参数类型,则不需要它们。当然,您ChildController需要一个类型定义。

于 2012-05-29T21:21:27.407 回答