2010-11-30 4 views
0

저는 Ninject를 처음 사용하고 있으며 stackoverflow도 새로 도입되었습니다. 여기Ninject 커널에서 인스턴스 가져 오기

public class MvcApplication : NinjectHttpApplication 
{ 
    protected override void OnApplicationStarted() 
    { 
     RegisterRoutes(RouteTable.Routes); 
    } 

    protected override IKernel CreateKernel() 
    { 
     var kernel = new StandardKernel(); 
     kernel.Load(AssemblyLocator.GetBinFolderAssemblies()); 
     return kernel; 
    } 
} 

그리고 bin 폴더에있는 모든 어셈블리를 검색 내 클래스 assemlylocator이입니다 :

나는 ninject.web.mvc 확장자를 사용하고,이 같은 올바르게 초기화 할 수 있었다 어셈블리의 모든 Ninject 모듈을 검색합니다.

public static class AssemblyLocator 
{ 
    private static readonly ReadOnlyCollection AllAssemblies = null; 
    private static readonly ReadOnlyCollection BinFolderAssemblies = null; 

    static AssemblyLocator() 
    { 
     AllAssemblies = new ReadOnlyCollection<Assembly>( 
      BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList()); 

     IList<Assembly> binFolderAssemblies = new List<Assembly>(); 

     string binFolder = HttpRuntime.AppDomainAppPath + "bin\\"; 
     IList<string> dllFiles = Directory.GetFiles(binFolder, "*.dll", 

     SearchOption.TopDirectoryOnly).ToList(); 

     foreach (string dllFile in dllFiles) 
     { 
      AssemblyName assemblyName = AssemblyName.GetAssemblyName(dllFile); 
      Assembly locatedAssembly = AllAssemblies.FirstOrDefault(a => 
      AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName)); 

      if (locatedAssembly != null) 
      { 
       binFolderAssemblies.Add(locatedAssembly); 
      } 
     } 

     BinFolderAssemblies = new ReadOnlyCollection<Assembly> (binFolderAssemblies); 
    } 

    public static ReadOnlyCollection<Assembly> GetAssemblies() 
    { 
     return AllAssemblies; 
    } 

    public static ReadOnlyCollection<Assembly> GetBinFolderAssemblies() 
    { 
     return BinFolderAssemblies; 
    } 
} 

모든 것이 내 컨트롤러에서 잘 작동 :

public class ReteController : Controller 
{ // // GET: /Rete/ 

    private readonly IReteService _service; 

    public ReteController(IReteService _service) 
    { 
     if (_service == null) 
     { 
      throw new ArgumentNullException("IReteService"); 
     } 
     this._service = _service; 
    } 

    public ActionResult Index() 
    { 
     return View(_service.getReti()); 
    } 

여기에 거의 모든 것을 쉽게 배울 때까지, 지금 내 문제는 내가에 바인딩 된 개체의 새 인스턴스를 생성해야하는 경우 NinjectModule from Ninject 커널에서 소리를 듣는 방법을 모른다.

//this is jus a ex. 

public ActionResult NewRete() { 
    IRete xItem = Kernel.get(); 
    xItem.name= "hope"; 
    return View(xItem); 
} 

문제점은 컨트롤러에서 커널을 찾을 수 없다는 것입니다. 나도 생성자에 그것을 주입해야합니까 ??

누군가가 나를 도울 수 있기를 바랍니다. 너희들이 온종일 나에게 줄 큰 도움을 주셔서 감사합니다.

답변

관련 문제