Unity IOC inject interface in ASP Control

北城以北 提交于 2019-12-13 08:18:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45216358/unity-ioc-inject-interface-in-asp-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!