Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/699923f216290cce2571 to your computer and use it in GitHub Desktop.
Save miklund/699923f216290cce2571 to your computer and use it in GitHub Desktop.
2011-08-24 Dependency Injection in ASP.NET WebForms
# Title: Dependency Injection in ASP.NET WebForms
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2011/08/24/dependency-injection-in-asp.net-webforms.html
<form id="form1" runat="server">
<div>
<h1>Products</h1>
<h2>Electronics</h2>
<asp:DataGrid
runat="server"
DataSource='<%# GetByType("Electronics") %>'
AutoGenerateColumns="true" OnLoad="DataBind" />
<h2>Candy</h2>
<asp:DataGrid
runat="server"
DataSource='<%# GetByType("Candy") %>'
AutoGenerateColumns="true" OnLoad="DataBind" />
</div>
</form>
public partial class ProductList : System.Web.UI.Page
{
[Dependency]
public IRepository<Product> Repository { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected IEnumerable<Product> GetByType(string type)
{
return Repository.Get(p => p.Type == type);
}
protected void DataBind(object sender, EventArgs e)
{
((Control) sender).DataBind();
}
}
[TestFixture]
public class ProductListCodeBehindShould
{
private class Template : ProductList
{
public Template()
{
Repository = new StubRepository();
}
public new IEnumerable<Product> GetByType(string type)
{
return base.GetByType(type);
}
private class StubRepository : IRepository<Product>
{
public IEnumerable<Product> Get(Func<Product, bool> criteria)
{
return new[]
{
new Product("Stereo", 120.0, "Electronics"),
new Product("Candy bar", 1.2, "Candy"),
new Product("Soda", 1.8, "Candy"),
new Product("Deep fried snickers bar", 0.2, "Candy")
}.Where(criteria);
}
}
}
[TestCase("Electronics", 120.0)]
[TestCase("Candy", 3.2)]
public void GetProductsBySpecifiedType(string type, double totalPrice)
{
/* Setup */
var template = new Template();
/* Test */
var products = template.GetByType(type);
/* Assert */
Assert.That(products.Sum(p => p.Price), Is.EqualTo(totalPrice));
}
}
public class UnityHttpModule : IHttpModule
{
private const string NamespacePrefix = "DIWebFormsExample";
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose()
{
// Nothing to dispose
}
// Get the controls in the page's control tree excluding the page itself
private static IEnumerable GetControlTree(Control root)
{
foreach (Control child in root.Controls)
{
yield return child;
foreach (Control c in GetControlTree(child))
{
yield return c;
}
}
}
private static void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
/* Static content */
if (HttpContext.Current.Handler == null)
{
return;
}
var handler = HttpContext.Current.Handler;
Unity.Instance.Container.BuildUp(handler.GetType(), handler);
// User Controls are ready to be built up after the page initialization is complete
var page = HttpContext.Current.Handler as Page;
if (page != null)
{
page.InitComplete += OnPageInitComplete;
}
}
// Build up each control in the page's control tree
private static void OnPageInitComplete(object sender, EventArgs e)
{
var page = (Page)sender;
foreach (Control c in GetControlTree(page))
{
var typeFullName = c.GetType().FullName ?? string.Empty;
var baseTypeFullName = c.GetType().FullName ?? string.Empty;
// Filter on namespace to avoid build up of System.Web components
if (typeFullName.StartsWith(NamespacePrefix) ||
baseTypeFullName.StartsWith(NamespacePrefix))
{
Unity.Instance.Container.BuildUp(c.GetType(), c);
}
}
}
}
<configuration>
<!-- IIS 6.0 and below -->
<system.web>
<httpModules>
<add name="UnityHttpModule" type="DIWebFormsExample.Lib.UnityHttpModule, DIWebFormsExample.Lib"/>
</httpModules>
</system.web>
<!-- IIS 7.0 and above -->
<system.webServer>
<modules>
<remove name="UnityHttpModule"/>
<add name="UnityHttpModule" type="DIWebFormsExample.Lib.UnityHttpModule, DIWebFormsExample.Lib"/>
</modules>
</system.webServer>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment