When do you contact ATC when departing from a non-towered airport into class D controlled airspace?
Class D is usually a cylinder so there's no shelf to be underneath; I'm assuming you're asking about departing from an uncontrolled airport that's actually in class D, like this one (N96):



Because class D goes to the surface I'd try to contact ATC on the ground before departure if possible, either on a regular frequency or via an RCO. And it would be worth checking the Chart Supplement for any local rules.

Otherwise, 14 CFR 91.129 says you should contact ATC as soon as you can after departure:


  (2) Departing flight. Each person—
  
  [...]
  
  (ii) From a satellite airport without an operating control tower, must
  establish and maintain two-way radio communications with the ATC
  facility having jurisdiction over the Class D airspace area as soon as
  practicable after departing.


There are some special cases like KDTS where you can't takeoff without contacting ATC first, but it's in a special rules area.