AutoFac: ASP.net WebForms UserControl Dependencies Only Available At Page_Load Event
2 min read
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 theOnInit
event already.public class MyUserControl : UserControlNote, the dependencies are autowired here over the public properties.
{
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
}
}
public class DependencyResolvingUserControl : UserControlAnd the according custom UserControl does now inherit from it
{
protected override void OnInit(EventArgs e)
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
cp.RequestLifetime.InjectProperties(this);
base.OnInit(e);
}
}
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
}
}