2009-08-13 5 views
4

현재 ASP.NET (표준, 이 아니고 MVC)이 아니므로 Ninject를 IOC 컨테이너로 사용하고 있습니다.Ninject, ASP.NET 및 사용자 지정 컨트롤

이미 내 페이지에 종속성을 주입하는 데 사용하고 있습니다. 그러나 사용자 지정 컨트롤에 종속성을 주입하는 방법이 있는지 궁금합니다.

하지 않으면, 나는 Ninject에 연장 진행 얻을 것이다 : 나는 Ninject에 연장 끝내었고, Ninject.Framework.Web의 DLL에 두 개의 클래스를 추가 있도록

답변

6

좋아요.

을 Heres 그것을 자신을 추가에 관심있는 사람을위한 패치 :

Index: src/Framework/Web/Ninject.Framework.Web.csproj 
=================================================================== 
--- src/Framework/Web/Ninject.Framework.Web.csproj (revision 158) 
+++ src/Framework/Web/Ninject.Framework.Web.csproj (working copy) 
@@ -2,7 +2,7 @@ 
    <PropertyGroup> 
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> 
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> 
- <ProductVersion>9.0.21022</ProductVersion> 
+ <ProductVersion>9.0.30729</ProductVersion> 
    <SchemaVersion>2.0</SchemaVersion> 
    <ProjectGuid>{C46075DB-A0FB-466B-BA76-C093227FA9C7}</ProjectGuid> 
    <OutputType>Library</OutputType> 
@@ -42,17 +42,24 @@ 
    <Reference Include="System.Core"> 
     <RequiredTargetFramework>3.5</RequiredTargetFramework> 
    </Reference> 
+ <Reference Include="System.Data" /> 
+ <Reference Include="System.Drawing" /> 
    <Reference Include="System.Web" /> 
    <Reference Include="System.Web.Services" /> 
+ <Reference Include="System.Xml" /> 
    </ItemGroup> 
    <ItemGroup> 
    <Compile Include="..\..\GlobalAssemblyInfo.cs"> 
     <Link>Properties\GlobalAssemblyInfo.cs</Link> 
    </Compile> 
+ <Compile Include="WebControlBase.cs" /> 
    <Compile Include="NinjectHttpApplication.cs" /> 
    <Compile Include="HttpHandlerBase.cs"> 
    </Compile> 
    <Compile Include="NinjectHttpModule.cs" /> 
+ <Compile Include="UserControlBase.cs"> 
+  <SubType>ASPXCodeBehind</SubType> 
+ </Compile> 
    <Compile Include="WebServiceBase.cs"> 
     <SubType>Component</SubType> 
    </Compile> 
Index: src/Framework/Web/UserControlBase.cs 
=================================================================== 
--- src/Framework/Web/UserControlBase.cs (revision 0) 
+++ src/Framework/Web/UserControlBase.cs (revision 0) 
@@ -0,0 +1,65 @@ 
+#region License 
+// 
+// Author: Nate Kohari <[email protected]>, Nik Radford <[email protected]> 
+// Copyright (c) 2007-2008, Enkari, Ltd. 
+// 
+// Licensed under the Apache License, Version 2.0 (the "License"); 
+// you may not use this file except in compliance with the License. 
+// You may obtain a copy of the License at 
+// 
+// http://www.apache.org/licenses/LICENSE-2.0 
+// 
+// Unless required by applicable law or agreed to in writing, software 
+// distributed under the License is distributed on an "AS IS" BASIS, 
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
+// See the License for the specific language governing permissions and 
+// limitations under the License. 
+// 
+#endregion 
+#region Using Directives 
+using System; 
+using Ninject.Core.Logging; 
+using Ninject.Core; 
+using System.Web.UI; 
+#endregion 
+ 
+namespace Ninject.Framework.Web 
+{ 
+ /// <summary> 
+ /// A <see cref="UserControl"/> that supports injection 
+ /// </summary> 
+ public class UserControlBase : UserControl 
+ { 
+  /*----------------------------------------------------------------------------------------*/ 
+  private ILogger _logger; 
+  /*----------------------------------------------------------------------------------------*/ 
+  /// <summary> 
+  /// Gets or sets the logger associated with the object. 
+  /// </summary> 
+  [Inject] 
+  public ILogger Logger 
+  { 
+   get { return _logger; } 
+   set { _logger = value; } 
+  } 
+  /*----------------------------------------------------------------------------------------*/ 
+  /// <summary> 
+  /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page. 
+  /// </summary> 
+  /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> 
+  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); 
+  } 
+  /*----------------------------------------------------------------------------------------*/ 
+ } 
+} 
Index: src/Framework/Web/WebControlBase.cs 
=================================================================== 
--- src/Framework/Web/WebControlBase.cs (revision 0) 
+++ src/Framework/Web/WebControlBase.cs (revision 0) 
@@ -0,0 +1,65 @@ 
+#region License 
+// 
+// Author: Nate Kohari <[email protected]>, Nik Radford <[email protected]> 
+// Copyright (c) 2007-2008, Enkari, Ltd. 
+// 
+// Licensed under the Apache License, Version 2.0 (the "License"); 
+// you may not use this file except in compliance with the License. 
+// You may obtain a copy of the License at 
+// 
+// http://www.apache.org/licenses/LICENSE-2.0 
+// 
+// Unless required by applicable law or agreed to in writing, software 
+// distributed under the License is distributed on an "AS IS" BASIS, 
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
+// See the License for the specific language governing permissions and 
+// limitations under the License. 
+// 
+#endregion 
+#region Using Directives 
+using System; 
+using System.Web.UI.WebControls; 
+using Ninject.Core.Logging; 
+using Ninject.Core; 
+#endregion 
+ 
+namespace Ninject.Framework.Web 
+{ 
+ /// <summary> 
+ /// A <see cref="WebControl"/> that supports injection 
+ /// </summary> 
+ public class WebControlBase : WebControl 
+ { 
+  /*----------------------------------------------------------------------------------------*/ 
+  ILogger _logger; 
+  /*----------------------------------------------------------------------------------------*/ 
+  /// <summary> 
+  /// Gets or sets the logger associated with the object. 
+  /// </summary> 
+  [Inject] 
+  public ILogger Logger 
+  { 
+   get { return _logger; } 
+   set { _logger = value; } 
+  } 
+  /*----------------------------------------------------------------------------------------*/ 
+  /// <summary> 
+  /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page. 
+  /// </summary> 
+  /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> 
+  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); 
+  } 
+  /*----------------------------------------------------------------------------------------*/ 
+ } 
+} 
+0

IE에서 가져온 서식있는 자료 대신 실제 XML을 게시 할 수 있습니까? –

+0

이것은 Ninject 용 SVN 패치입니다. ASP.NET에서 사용자 컨트롤과 사용자 정의 컨트롤과 함께 Ninject를 사용할 수있는 기능이 추가되었습니다. 작동했습니다. – Sekhat

+0

! 고맙습니다! – Seiti

0

나는 페이지의 모든 컨트롤을 통해 반복, 일부 인터페이스를 구현하는 사람들을 주입하여이 문제를 해결했다.

인터페이스는 비어 :

:

protected virtual void RequestActivation() 
{ 
    KernelContainer.Inject(this); 
    InjectControls(this.Controls); 
} 

private void InjectControls(ControlCollection controls) 
{ 
    foreach (Control control in controls) 
    { 
     if (control is INinjectControl) 
      KernelContainer.Inject(control); 
     this.InjectControls(control.Controls); 
    } 
} 

은 몇 가지 단점이 있습니다

public interface INinjectControl { } 

나는이 인터페이스를 구현하는 모든 컨트롤을 주입 PageBase 및 MasterPageBase에 루프를 추가 한

  • 이것은 OnInit가 실행될 때 이미 페이지에있는 컨트롤에서만 작동합니다. 프로세스에서 나중에 컨트롤을 추가하면 루프에 이 이미 실행되고 종속성이 주입되지 않습니다.
  • Controls 컬렉션을 요청하기 때문에이 컨트롤은 일부 컨트롤에서 CreateChildControls()를 호출합니다. 이 메서드는 이제 수명주기의 훨씬 이전에 호출되므로 문제가 발생할 수 있습니다.
  • 모든 컨트롤을 반복하므로 매우 효율적이지 않습니다.
관련 문제