We are using spring for our IOC container in an MVC3 project. I am trying to make a base controller that will have a constructor dependency on our IUserIdentity interface. I would like to define the constructor dependency once in the application context file for the abstract class and was hoping spring would be able to inject that for each derived class.
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;
}
}
I was hoping there was a way to define something like the following – (not sure how it would work) without re-defining the UserIdentity for every derived class.
<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>
As expected, when I do something like this, spring does not know what to put in for the first argument in the derived (ChildController) class.
Try referring to
ControllerBaseobject definition using theparentattribute:This will let
ChildController“inherit” the object definition fromControllerBase. See the spring.net docs for more on object definition inheritance. You might want to drop the index attributes from the constructor args, btw. They’re not needed if the constructor argument types can be resolved implicitly. And yourChildControllerneeds a type definition, of course.