Ninject.Web和用户控件

Che*_*hev 6 c# asp.net user-controls webforms ninject

我正在使用Ninject.Web库和我们的Web表单应用程序.它工作得很好,除了现在我需要将依赖注入到用户控件中.完成此任务的最佳方法是什么?Ninject.Web不包含与Web服务,页面和母版页类似的基类.

Pao*_*lla 4

您可以自己为用户控件创建一个基类:

public class NinjectedUserControl : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        RequestActivation();
    }

    /// <summary>
    /// Asks the kernel to inject this instance.
    /// </summary>
    protected virtual void RequestActivation()
    {
        KernelContainer.Inject(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的解决方案中有 Ninject.Web 的源代码,并且我已将此类添加到 Ninject.Web(因此它可以访问内部的 KernelContainer)。