MVC控制器 - 在控制器中注入2个存储库

时间:2011-10-19 15:36:49

标签: asp.net-mvc-3 ninject

我正在尝试将第二个存储库注入我的asp.net mvc 3控制器。我无法让它工作,不知道在哪里使用Ninject“添加另一个”。

我在global.asa.cs中有一个void函数

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

在我的控制器中,我有:

private INewsRepository _newsRepository;
private IContentRepository _contentRepository;

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

我如何为NewsController注册IContentRepository?

2 个答案:

答案 0 :(得分:3)

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

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

所以在你的第一个绑定下也可以这样做:

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

您可以拥有任意数量的绑定。

答案 1 :(得分:2)

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

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

所以对你来说,我可能会建议以下

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

在你的Global.asax中添加这个..

Bootstrapper.Bootstrap();

然后我建议你花一些时间在Google上阅读ninject约定。