Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

AutoFac: ASP.net WebForms UserControl Dependencies Only Available At Page_Load Event

2 min read

I'm currently adapting the architecture of one of our old but core projects, still written in ASP.net WebForms and with our custom ORM mapper. Since we're currently starting to release a new version of the project, we decided took the opportunity to also exchange our custom ORM mapper with Entity Framework and at the same time I introduced AutoFac for providing dependency injection. It turned out however, that with the default ASP.net WebForms integration, dependencies of a Page's child control (i.e. a UserControl) are only available in the Page_Load event of the UserControl rather than already in its OnInit.

The official AutoFac page has a nice article describing the integration into ASP.net Webforms: *click*. That worked out just fine with one exception. Normally our ASP.net pages contain very little logic. They're just aggregating a series of UserControls. As such I noticed that the dependencies inside those child UserControls are only available starting from the UserControl's Page_Load event whereas it would often be handy to have them in the OnInit event already.
public class MyUserControl : UserControl
{
public IServiceClass ServiceClass { get; set; }

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//ServiceClass.DoSomething(); //<< would not work as ServiceClass is at this point
}

protected void Page_Load(object sender, EventArgs e)
{
ServiceClass.DoSomething(); //works just fine
}
}
Note, the dependencies are autowired here over the public properties.
To avoid this, I used a BaseClass DependencyResolvingUserControl
public class DependencyResolvingUserControl : UserControl
{
protected override void OnInit(EventArgs e)
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
cp.RequestLifetime.InjectProperties(this);

base.OnInit(e);
}
}
And the according custom UserControl does now inherit from it
public class MyUserControl : DependencyResolvingUserControl
{
public IServiceClass ServiceClass { get; set; }

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ServiceClass.DoSomething(); //works
}

protected void Page_Load(object sender, EventArgs e)
{
ServiceClass.DoSomething(); //works as well
}
}

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus