Dependency Injection for Webforms asp.net

Ahmed Ghazey
Oct 27, 2020

--

Recently I was working on a legacy project where I required to Add ORM and Dependency Injection.

I faced a lot of problems due to webforms constructor must be empty it doesn’t allow parameterized constructors, simply the solution is using Parameter Injection, not constructor Injection, let’s explain in details what I made to complete the task:

1- Upgrade project .Net Framework environment to be at least 4.7.2

2-Install Microsoft.AspNet.WebFormsDependencyInjection.Unity

Install-Package Microsoft.AspNet.WebFormsDependencyInjection.Unity -Version 1.0.0Install-Package Unity -Version 5.11.7

Installing Unity will install more dependencies as well.

After installing the the packages we will write Interface in the base directory called IContainerAccessor.

using Unity;
public interface IContainerAccessor{
IUnityContainer Container { get; }}

Then we are going to Update Global.asax file

We have about 4 types of files (page, master, web services and user control)(.aspx, .Master, .asmx and .ascx), all the four files will be treated with the same manner.

We will create base class for each file, it will abstract class with generic type as following:

Final step we setup services , we will decorate our public services instances with [Dependency] attribute -Parameter Injection- and inherit from base service plus create empty constructor and invoke base() constructor:

That’s it Congratulations you made Dependency Injection for Web Forms application.

--

--

Ahmed Ghazey
Ahmed Ghazey

Written by Ahmed Ghazey

Seasoned Senior Staff Software Engineer with a proven track record of delivering complex software solutions, managing teams, and providing technical leadership.

No responses yet