Reputation: 2869
I want to inject an interface into an asp user control. My classes look like:
public partial class PercentByState : CommonControlsData
{
[Dependency]
public IChartService ChartService { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = ReportService.DoSomething();
}
}
}
public class CommonControlsData : System.Web.UI.UserControl
{
[Dependency]
public IReportService ReportService { get; set; }
}
I use Unity and Unity.WebForms nuget packages.
RegisterDependencies method looks like:
private static void RegisterDependencies( IUnityContainer container )
{
//services
container.RegisterType<IReportService, ReportService>();
}
ReportService and ChartService are null in Page_Load() function.
Any ideas what am I doing wrong ?
Edit: I am dynamically loading the controls with the following code:
TableRow tableRow = new TableRow();
TableCell tableCell = new TableCell();
string controlName = feature.ControlName;
tableCell.Controls.Add(Page.LoadControl(controlName));
tableRow.Controls.Add(tableCell);
MainContentTable.Rows.Add(tableRow);
Also, my controls are not registered to the page with a Register command. I think it has something to do with this type of loading.
Upvotes: 0
Views: 170
Reputation: 22655
Since you are dynamically loading controls you'll need to build them up manually:
TableRow tableRow = new TableRow();
TableCell tableCell = new TableCell();
string controlName = feature.ControlName;
var control = Page.LoadControl(controlName);
Context.GetChildContainer().BuildUp(control.GetType().UnderlyingSystemType, control);
tableCell.Controls.Add(control);
tableRow.Controls.Add(tableCell);
MainContentTable.Rows.Add(tableRow);
In order for Unity to BuildUp the control it will have to know the actual type of control to build up which is why the UnderlyingSystemType is used as the Type argument in the BuildUp
call. The alternative is to cast control to the appropriate type but that might not be known at compile time.
Upvotes: 1