1

I have a winform user control. In the constructor I instantiate a dependency. It goes like

public IProvider provider {get;set;}

public MyUserControl()
{
   InitializeComponent();
   provider = new MockProvider();//for testing. Will pass into constructor eventually
}

private void MyUserControl_Load(object sender, EventArgs e)
{
   SomeModel model = new SomeModel(provider);//provider is null
   //do work
   model.InsertIntoDb();
}

I thought member state persisted until you explicitly call Form.Close(). So why is the provider object null in the Load event?

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • @Shadow Wizard - I just dropped it onto the Form in design view. The Form's InitializeComponent() instantiates the user control. – P.Brian.Mackey Feb 09 '12 at 14:23
  • I believe the Design View won't create instance.. not sure though. Does the error also occur at runtime? – Shadow The GPT Wizard Feb 09 '12 at 15:05
  • I'm guessing your dev machine runs a 64-bit operating system. You'll have to use the DesignMode property to prevent this code from running in design mode. – Hans Passant Feb 10 '12 at 14:38
  • @HansPassant - Thanks for the tip hans. That would be a great change for new app dev. There's so much existing code right now that changing the way they do things would be a major headache. – P.Brian.Mackey Feb 13 '12 at 18:18

2 Answers2

0

This should work. Make sure the new keyword is in the constructor of the control and something is instantiating that control somewhere.

Make sure the new is called before the second function. Maybe it is other way around in this one. State should persist.

iefpw
  • 6,816
  • 15
  • 55
  • 79
0

InitializeComponent() was setting the Provider = null inside of the "parent" form (the one instantiating the user control). Turns out winforms don't support parameterless constructors very well.

Community
  • 1
  • 1
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348