Denny Solomona crossed for Castleford, but Wigan led at half-time against the run of play through Lewis Tierney's try and Matty Smith's penalty kick.
Grant Millington's try put the visitors back in front, before John Bateman went over to restore Wigan's two-point lead.
Nick Gregson got his first senior try and Bateman crossed again late on as Warriors climbed to third in the table.
Having suffered their heaviest defeat in Super League since 2005 with a 62-0 loss to Wakefield in their previous fixture, Wigan started slowly but were good value for their win after the break.
The hosts failed to take advantage when Luke Gale was sent to the sin-bin for dissent with the scores level in the first half, but Bateman's return to the side after two games out sparked the comeback.
Shaun Wane's team also welcomed back Dom Crosby, who made his first Super League appearance of the season having recovered from a hip injury.
Solomona moved clear as Super League's leading try-scorer with his 13th of the season, but Tigers were frustrated by improved Wigan defence in the second period as they suffered their fourth defeat in a row at the DW Stadium.
Wigan coach Shaun Wane:
"I don't want to keep going on about it. But, if you knew what we had gone through this week, there's so much toughness showed in that game against a really good Cas team.
"The admiration I have got for my players, the desire to grind out the win with the circumstances that nobody knows about is unbelievable.
"There were quite a few good performances, they are a good team and are well coached who know how to defend.
"We're not the biggest team, but I thought the way we defended was outstanding."
Castleford coach Daryl Powell:
"That last try gave the score a bit of an easier look than it was. It was tight all the way through.
"We lacked a little bit of quality in our play. I thought we defended awesome, they came at us in the second half with a game plan that put us under pressure.
"They made minimal errors and kicked well and we couldn't find a spark to get us out of yardage and into good field position.
"They deserved to win the game, they had more ball than us in decent field position and we had to work really hard to keep them out and that drained our energy reserves."
Wigan: Sarginson; Tierney, Bateman, Gildart, Charnley; Gregson, Smith; Mossop, Powell, Clubb, Tomkins, Isa, Sutton.
Replacements: Crosby, Tautai, Burke, Bretherton.
Castleford: Hampshire; Monaghan, Minikin, Webster, Solomona; Holmes, Gale; Lynch, Milner, Jewitt, Holmes, McMeeken, Massey.
Replacements: McShane, Millington, Maher, Cook.
Referee: Phil Bentham.
Wigan moved level on points with Super League leaders Warrington by coming from behind to beat Castleford.