2011-10-19 82 views
2

我想向我的asp.net mvc 3控制器注入第二个存储库。我无法使它工作,不知道在哪里使用Ninject“添加另一个”。MVC控制器 - 在控制器中注入2储存库

我在global.asa.cs

kernel.Bind<INewsRepository>().To<NewsRepository>(); 

而且在我的控制器我有一个void函数:

private INewsRepository _newsRepository; 
private IContentRepository _contentRepository; 

public NewsController(INewsRepository newsRepository, IContentRepository contentRepository) 
{ 
    this._newsRepository = newsRepository; 
    this._contentRepository = contentRepository; 
} 

如何注册IContentRepository为NewsController呢?

+1

你没有为'NewsController'声明相关性。你声明任何依赖于'INewsRepository'的类都使用指定的具体类。对'IContentRepository'做同样的事情,当ninject需要创建一个'NewsController'时,它会识别出有多个依赖关系。 –

回答

3

我使用autofac而不是Ninject,但基本保持不变。

如果你有你的第一个依赖注入工作,那么你应该能够绑定其他人。你只需要在Global.asax的Application_Start()中添加一个新的绑定。

所以,你的第一个结合也这么做:

kernel.Bind<IContentRepository>().To<ContentRepository>(); 

你可以有许多绑定,只要你喜欢。

+0

这就是答案,我一直都这样......我只是没有编译过的变化:S –

2

首先,将应用程序的引导程序移动到一个单独的位置是一种很好的做法。这使您的Global.asax保持清洁。

您还应该使用基于约定的注册。它最终会为您节省大量时间来处理不需要自定义的绑定。

因此,对于你我可能会建议以下

public static class Bootstrapper() 
{ 
    public static void Bootstrap() 
    { 
     kernel.Scan(k => 
     { 
     k.FromAssemblyContaining<INewsRepository>(); 
     k.BindWithDefaultConventions(); 
     }); 
    } 
} 

并在您的Global.asax中添加此..

Bootstrapper.Bootstrap(); 

那么我建议你花一些时间在谷歌阅读关于ninject约定。