【问题标题】:Can Spring.Net Inject an abstract class constructor arg for all derived classesSpring.Net可以为所有派生类注入抽象类构造函数arg吗
【发布时间】:2012-05-29 20:36:30
【问题描述】:

我们在 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) 类中为第一个参数输入什么。

【问题讨论】:

    标签: c# asp.net-mvc spring.net


    【解决方案1】:

    尝试使用parent 属性引用ControllerBase 对象定义:

    <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 中删除索引属性,顺便说一句。如果可以隐式解析构造函数参数类型,则不需要它们。当然,您的 ChildController 需要类型定义。

    【讨论】:

    • 谢谢!那工作得很好。另外,我喜欢删除索引花絮。
    • 很好听;当你在这里使用构造函数注入时,检查autowiring 可能也是值得的。在构造函数注入的情况下,我发现 autowring 工作得相当好。
    • Autowire 运行良好。我想我认为自动装配是一个应用程序范围的设置(我们的一些接口有多种类型,因此必须指定构造函数参数)。
    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 2021-07-15
    • 2019-04-02
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多