Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Dependency Injection with ASP.NET Web Forms

I am trying to work out a way to use dependency injection with ASP.NET Web Forms controls.

I have got lots of controls that create repositories directly, and use those to access and bind to data etc.

I am looking for a pattern where I can pass repositories to the controls externally (IoC), so my controls remain unaware of how repositories are constructed and where they come from etc.

I would prefer not to have a dependency on the IoC container from my controls, therefore I just want to be able to construct the controls with constructor or property injection.

(And just to complicate things, these controls are being constructed and placed on the page by a CMS at runtime!)

Any thoughts?

like image 971
Jack Ukleja Avatar asked Feb 26 '09 06:02

Jack Ukleja


People also ask

Can we use dependency injection in asp net?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

What is dependency injection in Webapi?

What is Dependency Injection? A dependency is any object that another object requires. For example, it's common to define a repository that handles data access. Let's illustrate with an example.

How can dependency injection be implemented in C#?

Using dependency injection, we modify the constructor of Runner to accept an interface ILogger, instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner's constructor.


1 Answers

UPDATE 2019: With the introduction of Web Forms 4.7.2, there is now better support for DI. This invalidates the below. See: Wiring up Simple Injector in WebForms in .NET 4.7.2

You can use automatic constructor injection by replacing the default PageHandlerFactory with a custom one. This way you can use an overloaded constructor to load the dependencies. Your page might look like this:

public partial class HomePage : System.Web.UI.Page {     private readonly IDependency dependency;      public HomePage(IDependency dependency)     {         this.dependency = dependency;     }      // Do note this protected ctor. You need it for this to work.     protected HomePage () { } } 

Configuring that custom PageHandlerFactory can be done in the web.config as follows:

<?xml version="1.0"?> <configuration>   <system.web>     <httpHandlers>       <add verb="*" path="*.aspx"         type="YourApp.CustomPageHandlerFactory, YourApp"/>     </httpHandlers>   </system.web> </configuration> 

Your CustomPageHandlerFactory can look like this:

public class CustomPageHandlerFactory : PageHandlerFactory {     private static object GetInstance(Type type)     {         // TODO: Get instance using your favorite DI library.         // for instance using the Common Service Locator:         return Microsoft.Practices.ServiceLocation             .ServiceLocator.Current.GetInstance(type);     }      public override IHttpHandler GetHandler(HttpContext cxt,          string type, string vPath, string path)     {         var page = base.GetHandler(cxt, type, vPath, path);          if (page != null)         {             // Magic happens here ;-)             InjectDependencies(page);         }          return page;     }      private static void InjectDependencies(object page)     {         Type pageType = page.GetType().BaseType;          var ctor = GetInjectableCtor(pageType);          if (ctor != null)         {             object[] arguments = (                 from parameter in ctor.GetParameters()                 select GetInstance(parameter.ParameterType)                 .ToArray();              ctor.Invoke(page, arguments);         }     }      private static ConstructorInfo GetInjectableCtor(         Type type)     {         var overloadedPublicConstructors = (             from constructor in type.GetConstructors()             where constructor.GetParameters().Length > 0             select constructor).ToArray();          if (overloadedPublicConstructors.Length == 0)         {             return null;         }          if (overloadedPublicConstructors.Length == 1)         {             return overloadedPublicConstructors[0];         }          throw new Exception(string.Format(             "The type {0} has multiple public " +             "ctors and can't be initialized.", type));     } } 

Downside is that this only works when running your side in Full Trust. You can read more about it here. But do note that developing ASP.NET applications in partial trust seems a lost cause.

like image 134
Steven Avatar answered Sep 20 '22 17:09

Steven