2017-07-20 13 views
0

我想注入一个接口到asp用户控件。我的课程如下所示:统一IOC注入接口在ASP控制

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; } 
} 

我使用Unity和Unity.WebForms nuget包。

RegisterDependencies方法看起来像:

private static void RegisterDependencies(IUnityContainer container) 
    { 
     //services 
     container.RegisterType<IReportService, ReportService>(); 
    } 

ReportService的的ChartService的Page_Load()函数空。

任何想法我做错了什么?

编辑: 我动态加载控件用下面的代码:

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); 

而且,我的控件未注册的页面与注册命令。我认为这与这种加载类型有关​​。

+0

通常,对于标记为“依赖”的ASP.NET WebForms Page属性是注入的内容。如果UserControls不是页面依赖关系,那么我认为它们不会被Unity构建。 –

+0

然后我如何注入用户控件? –

+0

我想我错了......如果你使用的是Unity.WebForms,那么它看起来像所有的控件应该建立(和注入的依赖关系)。很难说你发布了什么问题 - 发布Minimal,Complete和Verifiable示例会有所帮助(虽然涉及很多文件)。其他要考虑的事情:是否注入了任何*依赖关系,或者它只是儿童控制的一个问题,UnityHttpModule是否已注册? –

回答

1

既然你是动态加载控件,你需要手动建立他们:

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); 

为了团结累积控制它必须知道实际的控制类型的建立是为什么在BuildUp调用中使用UnderlyingSystemType作为Type参数。另一种方法是将控件转换为适当的类型,但在编译时可能不知道。

+0

我最终继承了泛型类的所有控件,并将接口移动到该类。如果有人需要我的代码,请给我留言。 –