InjectionConstructor/DI w/ inheritance

Topics: CAB & Smart Client Software Factory
Feb 2, 2006 at 10:59 AM
originally posted by: samkuehn

I have a base presenter class that initializes some services for me:
constructor looks like:
InjectionConstructor
public PresenterBase
(
ServiceDependency WorkItem workItem,
ServiceDependency IUserServiceAgent userServiceAgent,
)
{
m_WorkItem = workItem;
m_UserServiceAgent = userServiceAgent;
}
I then have public accessors of the services:
public IUserServiceAgent UserServiceAgent
{
get
{
return m_UserServiceAgent;
}
}

I would like other presenters to inherit from this BasePresenter class but am unsure of how to get the dependency injection/InjectionConstuctor stuff to work right. Is this possible? What will the derived class look like?
Feb 2, 2006 at 11:52 AM
originally posted by: BradWilsonMSFT

There is no "constructor inheritance" in .NET. You will have to re-define the constructor, with its attributes, in the base classes.

Alternatively, you can use injection on properties/methods instead of constructors. Since these things do inherit, there is no re-definition required. In my opinion, when you're writing a base class, using the non-constructor injection options are usually a better choice.
Feb 2, 2006 at 1:37 PM
originally posted by: samkuehn

If I understand you correctly things would look something like this. I must call the Initialize() method from the constructor in the derived class as it is created using the CreateNew attribute in the view. I am a little confused on exact syntax.

//DerivedPresenter : BasePresenter
InjectionConstructor
public DerivedPresenter()
{
//How I call this?
base.Initialize();
}

//BasePresenter
Initialize
(
ServiceDependency WorkItem workItem,
ServiceDependency IUserServiceAgent userServiceAgent,
)
{
m_WorkItem = workItem;
m_UserServiceAgent = userServiceAgent;
}

public IUserServiceAgent UserServiceAgent
{
get
{
return m_UserServiceAgent;
}
}

Am I heading in the right direction?
Feb 4, 2006 at 7:56 AM
originally posted by: WalkingDisaster

First, if your base presenter extends Controller, you'll already have the WorkItem service dependency injected (Controller.WorkItem).

Second, just decorate your property with ServiceDependencyAttribute instead of your constructor. Whenever BuildUp encounters an implementing class, it will inject your service using the property setter.

using System;
using Microsoft.Practices.CompositeUI;

namespace Whatever.Whatever
{
public abstract class BasePresenter : Controller
{
private IUserServiceAgent userServiceAgent;

protected BasePresenter() : base() { }

ServiceDependency
public IUserServiceAgent UserServiceAgent
{
get { return this.userServiceAgent; }
set { this.userServiceAgent = value; }
}
}
}