Using Dependency Injection in a website can get a little dodgy, but in my ASP.NET site use the same base code as my WPF app, I needed a little dependency injection to resolve references at runtime when the application type is known. Now in your ASP.NET page just like in your WPF application you need a little extra bit to get it all going. Finding this for WPF is easy, not so much in ASP.
Imports System.Web
Imports System.Web.UI
Imports Microsoft.Practices.Unity
''' <summary>
''' C# version and source
''' http://blogs.msdn.com/mpuleio/archive/2008/07/17/proof-of-concept-a-simple-di-solution-for-asp-net-webforms.aspx
''' </summary>
''' <remarks></remarks>
Public Class UnityHttpModule
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute
End Sub
Private Sub OnPreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
Dim handler As IHttpHandler = HttpContext.Current.Handler
If TypeOf handler Is Page Then
My.Unity.Container.BuildUp(handler.GetType(), handler)
' User Controls are ready to be built up after the page initialization is complete
Dim page As Page = handler
If Not page Is Nothing Then
AddHandler page.InitComplete, AddressOf OnPageInitComplete
End If
End If
End Sub
Private Sub OnPageInitComplete(ByVal sender As Object, ByVal e As EventArgs)
Dim page As Web.UI.Page = sender
For Each c In BuildControlTree(page)
Try
My.Unity.Container.BuildUp(c.GetType(), c)
Catch ex As Exception
' TODO: Some sort of error handling if important
WebPortalTrace.Verbose(WebPortalTraceType.Unity, "Unity unable to build up {0}", c.GetType)
End Try
Next
End Sub
' Get the controls in the page's control tree excluding the page itself
Private Function BuildControlTree(ByVal root As Control) As List(Of Control)
Dim ct As New List(Of Control)
For Each c In root.Controls
ct.Add(c)
ct.AddRange(BuildControlTree(c))
Next
Return ct
End Function
End Class
All you need is to put a reference into your config file:
<system.web>
<httpModules>
<add name="UnityHttpModule" type="Company.Product.UnityHttpModule, Company.Product"/>
</httpModules>
</system.web>
And off you go, before you know it you will have dependency injection coming out of your ears.
One of the advantages to using dependency injection is that you could change a piece of functionality without having to recompile and redeploy your site! How about this…
<unity>
<containers>
<container>
<types>
<type type="Company.Product.ViewModels.IRecentItemsViewModel, Company.Product" mapTo="Company.Product.ViewModels.RecentItemsViewModel, Company.Product" />
</types>
</container>
</containers>
</unity>
The business then decide that they have to have the order of the recent items list changed but that it needs to go into production immediately, so your testing cycle is extremely tight. No problem… fire up a new solution and create a new class that inherits from IRecentItemsViewModel and implement the new functionality. Then compile it as “Company.Product.Hotfix1”, drop it into your test site bin folder and change line above to:
<unity>
<containers>
<container>
<types>
<type type="Company.Product.ViewModels.IRecentItemsViewModel, Company.Product" mapTo="Company.Product.Hotfix1.ViewModels.RecentItemsViewModel, Company.Product.Hotfix1" />
</types>
</container>
</containers>
</unity>
The site will then load your new code and you can test the only functionality that you have changed, before deploying to production. Now this may not seam like much, but if your system is made up of thousands of views then you may just need this functionality. And it is so easy to achieve that even for small projects it is fantastic.
P.S. Works with MVC… shhhh…
Technorati Tags: Software Development .NET CodeProject WPF
Smart Classifications
Each classification [Concepts, Categories, & Tags] was assigned using AI-powered semantic analysis and scored across relevance, depth, and alignment. Final decisions? Still human. Always traceable. Hover to see how it applies.
What to read next
Wpf Ninject Dojo: The Data Provider
Explains how to use a custom NinjectDataProvider in WPF to enable dependency injection for ViewModels, improving flexibility and design-time …
My.Unity.Resolve(Of Ninja)
Shows how to create a shared UnityContainer singleton in VB.NET using the “My” namespace, enabling dependency injection across WPF and …
Creating a Data Access layer using Unity
Learn how to build a flexible data access layer in .NET using Unity for dependency injection, interface mapping, and factory patterns with …
Reformat your CSS on the fly
Learn how to use a .NET HTTP handler to dynamically adjust CSS file paths, ensuring images and resources load correctly across different web …
TFS Sticky Buddy layout fun
A developer shares challenges and insights from building a TFS Sticky Buddy UI in WinForms and WPF, comparing layout issues and ease of use …
Mastering Site Reliability: Insights from Azure DevOps on Building a Resilient Live Site Culture
Explore proven strategies from Azure DevOps for building resilient, reliable software systems, covering transparency, automation, telemetry, …
Detecting agile theatre with real delivery signals
Why Most Companies Operating Models Fail in Dynamic Markets
A concise comparison of Predictive and Adaptive Operating Models, explaining why traditional structures fail in dynamic markets and how …
Don’t Manage Dependencies, Remove Them
Explains why dependencies are a sign of poor system design and outlines steps to eliminate them by aligning teams, clarifying ownership, and …
The Estimation Trap: How Tracking Accuracy Undermines Trust, Flow, and Value in Software Delivery
Tracking estimation accuracy in software delivery leads to mistrust, fear, and distorted behaviours. Focus on customer value, flow, and …
Flow of Value vs Flow of Work – Misnomer or Useful Shorthand?
Compares “flow of value” and “flow of work” in Kanban, explaining why only validated outcomes count as value and stressing the need for …
Why Outsourcing DevOps Fails, and How Real Engineering Excellence Starts With Your Team
Avoid DevOps vendor lock-in, discover how true engineering excellence starts with partnership, not outsourcing. Ready to transform your …
Detecting agile theatre with real delivery signals
Don’t Manage Dependencies, Remove Them
Explains why dependencies are a sign of poor system design and outlines steps to eliminate them by aligning teams, clarifying ownership, and …
The Estimation Trap: How Tracking Accuracy Undermines Trust, Flow, and Value in Software Delivery
Tracking estimation accuracy in software delivery leads to mistrust, fear, and distorted behaviours. Focus on customer value, flow, and …
Flow of Value vs Flow of Work – Misnomer or Useful Shorthand?
Compares “flow of value” and “flow of work” in Kanban, explaining why only validated outcomes count as value and stressing the need for …
Why Outsourcing DevOps Fails, and How Real Engineering Excellence Starts With Your Team
Avoid DevOps vendor lock-in, discover how true engineering excellence starts with partnership, not outsourcing. Ready to transform your …
Estimating Better in an Overloaded System Is a Poor Man’s Strategy
High work in progress (WIP) causes delays and unpredictability; improving estimates won’t help. Limiting WIP and focusing on flow is key to …