Controller.WorkItem not set correctly

Topics: CAB & Smart Client Software Factory
Feb 13, 2006 at 12:17 AM
originally posted by: RossNeilson

I have set up a typical Windows Forms Mdi application using Cab. The shell form contains a menu item which, when clicked, creates and runs a FindOrderWorkItem. The code to do this is as follows-

private void OnFindOrderClicked(object sender, EventArgs e)
{
FindOrderWorkItem workItem = this.RootWorkItem.WorkItems.AddNew<FindOrderWorkItem>();
workItem.Run();
workItem.Show(this.RootWorkItem.Workspaces"MdiWorkspace");
}

The FindOrderWorkItem class contains a dependency-injected FindOrderController, defined as follows-

Dependency(CreateType=typeof(FindOrderController), Name="Controller")
public FindOrderController Controller
{
get { return _controller; }
set { _controller = value; }
}

I expected, perhaps incorrectly, that the WorkItem property of the Controller would be the FindOrderWorkItem, when in fact it is the RootWorkItem. In order to work around this I have overriden OnRunStarted, as follows-

protected override void OnRunStarted()
{
base.OnRunStarted();
this.Controller.WorkItem = this;
}

I would prefer not to have to do this though. Does anyone have any suggestions as to what I am doing wrong?
Feb 13, 2006 at 6:57 AM
originally posted by: BradWilsonMSFT

Dependency injection within a WorkItem doesn't work exactly as you'd expect. That's because the WorkItem is the core part of the dependency injection system, so creating items on its behalf halfway through its own creation can cause oddities.

Remove the Dependency attribute from the Controller property and use explicit item creation in OnRunCalled instead:

private FindOrderController _controller;

public FindOrderController Controller
{
get { return _controller; }
}

protected override OnRunStarted()
{
base.OnRunStarted();
_controller = Items.AddNew<FindOrderController>("Controller");
}
Feb 13, 2006 at 9:08 AM
originally posted by: RossNeilson

Brad,

Thanks for setting me straight on that one. Is there any particular reason that you recommended creating the Controller in OnRunStarted() rather than OnInitialized() ?
Feb 13, 2006 at 7:45 PM
originally posted by: BradWilsonMSFT

No, no reason in particular. I was just taking your existing code and making small modifications. :)