我有一個aspx頁面,我想注入一個用戶控件的引用。用戶控件存儲在單獨的程序集中並在運行時加載。在注入用戶控件之後,它應該被加載到頁面的控件集合中。在WebForms中注入一個Web用戶控件與Ninject
一切似乎正常工作期望的點添加到頁面的控制。沒有錯誤,但控件的用戶界面不顯示。
的global.asax.cs
protected override Ninject.IKernel CreateKernel()
{
var modules = new INinjectModule[] { new MyDefaultModule() };
var kernel = new StandardKernel(modules);
// Loads the module from an assembly in the Bin
kernel.Load("ExternalAssembly.dll");
return kernel;
}
,這裏是外部模塊是如何在其他組件中定義:
public class ExternalModule : NinjectModule
{
public ExternalModule() { }
public override void Load()
{
Bind<IView>().To<controls_MyCustomUserControlView>();
}
}
調試器顯示,當應用程序運行時,負載上外部模塊正在被調用,並且依賴被注入到頁面中。
public partial class admin_MainPage : PageBase
{
[Inject]
public IView Views { get; set; }
在這一點上,當試圖添加視圖(這裏是一個用戶控件)到頁面,沒有任何顯示。這是否與用戶控件由Ninject創建的方式有關?加載的控件似乎有一個空的控件集合。
aspx頁面內
var c = (UserControl)Views;
// this won't show anything. even the Control collection of the loaded control (c.Controls) is empty
var view = MultiView1.GetActiveView().Controls.Add(c);
// but this works fine
MultiView1.GetActiveView().Controls.Add(new Label() { Text = "Nice view you got here..." });
終於視圖/用戶控件:
public partial class controls_MyCustomUserControlView : UserControl, IView
{
}
它僅包含一個標籤:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyCustomUserControlView.ascx.cs" Inherits="controls_MyCustomUserControlView" %>
<asp:Label Text="Wow, what a view!" runat="server" />
之前有人建議MEF或System.Addin,我已經嘗試過它們。 – yanta 2010-12-16 17:35:29