We are currently working with an older project (ASP.NET Web Forms Website) and trying to see if we can set up dependency injection for it.
Need to emphasize: this is NOT a Web Application project... it's the older type, the Website.
It is currently targeting .NET 4.7.2:
<httpRuntime targetFramework="4.7.2" />
So far, we've included the NuGet package:
<package id="Microsoft.AspNet.WebFormsDependencyInjection.Unity" version="1.0.0" targetFramework="net472" />
Defined some dummy interface and implementations:
public interface IDependencyTest
{
string GetName();
}
public class DependencyTest : IDependencyTest
{
public string GetName()
{
return "Mwuhahaha!!!";
}
}
And wired the DI container in the Application_Start event handler in global.asax:
void Application_Start(object sender, EventArgs e)
{
var container = this.AddUnity();
container.RegisterType<IDependencyTest, DependencyTest>();
}
Required namespaces were imported:
<%@ Import Namespace="Microsoft.AspNet.WebFormsDependencyInjection.Unity" %>
<%@ Import Namespace="Unity" %>
Created a test page Teste.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Teste.aspx.cs" Inherits="Teste" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDisplay" runat="server" Text="No luck..."></asp:Label>
</div>
</form>
</body>
</html>
With the following code behind:
public partial class Teste : System.Web.UI.Page
{
private IDependencyTest _dependencyTest;
public Teste(IDependencyTest dependencyTest)
{
_dependencyTest = dependencyTest;
}
protected void Page_Load(object sender, EventArgs e)
{
lblDisplay.Text = _dependencyTest.GetName();
}
}
All this setup will fail with the following exception:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\7a04dd72\81815e95\App_Web_teste.aspx.cdcab7d2.rtms4_ja.0.cs(187): error CS7036: There is no argument given that corresponds to the required formal parameter 'dependencyTest' of 'Teste.Teste(IDependencyTest)'
However, property injection does work:
using Unity.Attributes;
public partial class Teste : System.Web.UI.Page
{
[Dependency]
public IDependencyTest DependencyTest { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
lblDisplay.Text = DependencyTest.GetName();
}
}
To be honest, I'd really like to use the constructor injection...
Why isn't it working with our current setup?
Is it because it's a ASP.NET Website and NOT an ASP.NET WebApplication?
Can anything be done to get it working here, also?