2011-02-08 150 views

回答

0

檢查Steve Sanderson(Apress)的書「Pro ASP.NET MVC 2 Framework,2nd Edition」。作者使用Ninject連接數據庫。我認爲你可以使用這些例子並使它們適應你的需求。

+0

是的,我有這觸發我問這個問題。如果Web應用程序是Web表單,它是如何完成的? – nellbryant 2011-02-08 14:01:54

+0

這也是我通常在WebForms中進行的。訣竅是你需要使用內核的Get方法。 – Didaxis 2011-10-28 15:45:57

4

查看Ninject.Web擴展。它提供了基礎設施 https://github.com/ninject/ninject.web

+0

嗨雷莫。這似乎沒有顯示任何Web窗體的例子。 – nellbryant 2011-02-08 14:46:02

+5

我知道我應該以身作則,但自述文件應該> 0字節! – 2011-02-08 22:41:10

+0

@Ruben:我同意更新文件是列表atm中的高級任務之一。 – 2011-02-09 01:14:37

9

我想這裏是在ASP.NET Web窗體上實現Ninject.Web的步驟。

  1. 在Global.asax實現NinjectHttpApplication。對於內核,通過實現NinjectModule來傳遞它。
  2. 在每個Web窗體頁面加載事件後面的代碼,實現Ninject.Web.PageBase。在其上添加[Inject]過濾器的實例類。

對於更詳細的例子,下面是我發現了一些有用的鏈接:

1. http://joeandcode.net/post/Ninject-2-with-WebForms-35

2. http://davidhayden.com/blog/dave/archive/2008/06/20/NinjectDependencyInjectionASPNETWebPagesSample.aspx

72

下面是使用Ninject與的WebForms的步驟。

第一步 - 下載

有需要兩個下載 - Ninject-2.0.0.0-release-net-3.5和web窗體延伸Ninject.Web_1.0.0.0_With.log4net(有一個NLOG替代)。

需要在Web應用程序中引用以下文件:Ninject.dll,Ninject.Web.dll,Ninject.Extensions.Logging.dll和Ninject.Extensions.Logging.Log4net.dll。

步驟2 - 的Global.asax

全球類需要從Ninject.Web.NinjectHttpApplication導出並實施CreateKernel(),它創建容器:

using Ninject; using Ninject.Web; 

namespace Company.Web { 
    public class Global : NinjectHttpApplication 


     protected override IKernel CreateKernel() 
     { 
      IKernel kernel = new StandardKernel(new YourWebModule()); 
      return kernel; 
     } 

StandardKernel構造函數採用一個Module

步驟3 - 模塊

的模塊,在這種情況下YourWebModule,定義所有綁定的web應用程序將需要:

using Ninject; 
using Ninject.Web; 

namespace Company.Web 
{ 
    public class YourWebModule : Ninject.Modules.NinjectModule 
    { 

     public override void Load() 
     { 
      Bind<ICustomerRepository>().To<CustomerRepository>(); 
     } 

在這個例子中,在任何使用ICustomerRepository接口被引用的將使用具體CustomerRepository

第4步 - 網頁

一旦這樣做了每個頁面都需要從Ninject.Web.PageBase繼承:

using Ninject; 
    using Ninject.Web; 
    namespace Company.Web 
    { 
     public partial class Default : PageBase 
     { 
      [Inject] 
      public ICustomerRepository CustomerRepo { get; set; } 

      protected void Page_Load(object sender, EventArgs e) 
      { 
       Customer customer = CustomerRepo.GetCustomerFor(int customerID); 
      } 

InjectAttribute -[Inject] - 告訴Ninject注入ICustomerRepository到CustomerRepo屬性。

如果你已經有了一個基頁,你只需要讓你的基頁從Ninject.Web.PageBase派生。

第5步 - 母版頁

不可避免地,你就會有母版頁,並允許母版訪問注入你需要從Ninject.Web.MasterPageBase派生母版頁對象:

using Ninject; 
using Ninject.Web; 

namespace Company.Web 
{ 
    public partial class Site : MasterPageBase 
    { 

     #region Properties 

     [Inject] 
     public IInventoryRepository InventoryRepo { get; set; }  

第6步 - 靜態Web服務方法

接下來的問題是不能夠注入到靜態方法。我們有幾個Ajax PageMethods,它們顯然是靜態的,所以我必須將這些方法轉換爲標準的Web服務。同樣,網絡服務需要從Ninject類派生 - Ninject.Web.WebServiceBase

using Ninject; 
using Ninject.Web;  
namespace Company.Web.Services 
{ 

    [WebService(Namespace = "//tempuri.org/">http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
    [System.Web.Script.Services.ScriptService] 
    public class YourWebService : WebServiceBase 
    { 

     #region Properties 

     [Inject] 
     public ICountbackRepository CountbackRepo { get; set; } 

     #endregion 

     [WebMethod] 
     public Productivity GetProductivity(int userID) 
     { 
      CountbackService _countbackService = 
       new CountbackService(CountbackRepo, ListRepo, LoggerRepo); 

在JavaScript中,您需要引用標準服務 - Company.Web.Services.YourWebService.GetProductivity(user, onSuccess),而不是PageMethods.GetProductivity(user, onSuccess)

我發現的唯一的其他問題是將對象注入用戶控件。儘管可以使用Ninject功能創建您自己的基本UserControl,但我發現將屬性添加到所需對象的用戶控件並在容器頁面中設置屬性會更快。我認爲支持UserControls是在Ninject的「待辦事項」列表中。

添加Ninject非常簡單,它是一個雄辯的IoC解決方案。許多人喜歡它,因爲沒有Xml配置。它還有其他有用的「技巧」,例如只用Ninject語法將對象變成單例 - Bind<ILogger>().To<WebLogger>().InSingletonScope()。沒有必要把WebLogger改成實際的Singleton實現,我喜歡這個。

65

隨着Ninject v3.0的發佈(2012年4月12日起),它變得更加容易。注入是通過HttpModule實現的,因此不需要讓頁面從自定義頁面/母版頁繼承。這裏是快速秒殺的步驟(和代碼)。

  1. 創建一個新的ASP.NET Web窗體項目
  2. 使用的NuGet添加Ninject.Web LIB(這也將拉低Ninject.Web.Common和Ninject庫)
  3. 註冊您的自定義綁定在App_Start/NinjectWebCommon。CS/RegisterServices方法
  4. 使用屬性注入您的網頁上

NinjectWebCommon/RegisterServices

/// <summary> 
    /// Load your modules or register your services here! 
    /// </summary> 
    /// <param name="kernel">The kernel.</param> 
    private static void RegisterServices(IKernel kernel) 
    { 
     kernel.Bind<IAmAModel>().To<Model1>(); 
    } 

默認

public partial class _Default : System.Web.UI.Page 
{ 

    [Inject] 
    public IAmAModel Model { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     System.Diagnostics.Trace.WriteLine(Model.ExecuteOperation()); 
    } 
} 

的Site.Master

public partial class SiteMaster : System.Web.UI.MasterPage 
{ 

    [Inject] 
    public IAmAModel Model { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     System.Diagnostics.Trace.WriteLine("From master: " 
      + Model.ExecuteOperation()); 
    } 
} 

模型

public interface IAmAModel 
{ 
    string ExecuteOperation();   
} 

public class Model1 : IAmAModel 
{ 
    public string ExecuteOperation() 
    { 
     return "I am a model 1"; 
    } 
} 

public class Model2 : IAmAModel 
{ 
    public string ExecuteOperation() 
    { 
     return "I am a model 2"; 
    } 
} 

從輸出窗口

I am a model 1 
From master: I am a model 1 
9

The answer here結果目前不工作由於open bug。這是@ Jason步驟的一個修改版本,它使用客戶httpmodule來注入頁面和控件,而不需要從ninject類繼承。

  1. 創建一個新的ASP.NET Web窗體項目
  2. 使用的NuGet添加Ninject.Web LIB
  3. 註冊您的自定義綁定在App_Start/NinjectWebCommon.cs/RegisterServices方法
  4. 添加InjectPageModule和註冊在NinjectWebCommon
  5. 使用屬性注入您的網頁

InjectPageModule.cs

public class InjectPageModule : DisposableObject, IHttpModule 
{ 
    public InjectPageModule(Func<IKernel> lazyKernel) 
    { 
     this.lazyKernel = lazyKernel; 
    } 

    public void Init(HttpApplication context) 
    { 
     this.lazyKernel().Inject(context); 
     context.PreRequestHandlerExecute += OnPreRequestHandlerExecute; 
    } 

    private void OnPreRequestHandlerExecute(object sender, EventArgs e) 
    { 
     var currentPage = HttpContext.Current.Handler as Page; 
     if (currentPage != null) 
     { 
      currentPage.InitComplete += OnPageInitComplete; 
     } 
    } 

    private void OnPageInitComplete(object sender, EventArgs e) 
    { 
     var currentPage = (Page)sender; 
     this.lazyKernel().Inject(currentPage); 
     this.lazyKernel().Inject(currentPage.Master); 
     foreach (Control c in GetControlTree(currentPage)) 
     { 
      this.lazyKernel().Inject(c); 
     } 

    } 

    private IEnumerable<Control> GetControlTree(Control root) 
    { 
     foreach (Control child in root.Controls) 
     { 
      yield return child; 
      foreach (Control c in GetControlTree(child)) 
      { 
       yield return c; 
      } 
     } 
    } 

    private readonly Func<IKernel> lazyKernel; 
} 

NinjectWebCommon/RegisterServices

private static void RegisterServices(IKernel kernel) 
    { 
     kernel.Bind<IHttpModule>().To<InjectPageModule>(); 
     kernel.Bind<IAmAModel>().To<Model1>(); 

    } 

默認

public partial class _Default : System.Web.UI.Page 
{ 

    [Inject] 
    public IAmAModel Model { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     System.Diagnostics.Trace.WriteLine(Model.ExecuteOperation()); 
    } 
} 

的Site.Master

public partial class SiteMaster : System.Web.UI.MasterPage 
{ 

    [Inject] 
    public IAmAModel Model { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     System.Diagnostics.Trace.WriteLine("From master: " 
      + Model.ExecuteOperation()); 
    } 
} 

模型

public interface IAmAModel 
{ 
    string ExecuteOperation();   
} 

public class Model1 : IAmAModel 
{ 
    public string ExecuteOperation() 
    { 
     return "I am a model 1"; 
    } 
} 

public class Model2 : IAmAModel 
{ 
    public string ExecuteOperation() 
    { 
     return "I am a model 2"; 
    } 
} 

結果從輸出窗口

I am a model 1 
From master: I am a model 1