2012-02-02 65 views
2

如何使用Ninject將對象傳遞給構造函數參數?假設對象在容器中註冊。如何定義構造函數參數以使用ninject自定義對象?

+0

如果您提供給我們的有限的細節隱藏了對多級上下文的需求,請針對Ninject Context保留一個Google。 (雖然我剛剛意識到你也是回答者,所以可能不會,Doh!)。還有,如果你用一個帶有ConstructorArgument的WithParameter,它具有'inherit'(類似的東西)參數設置爲true' – 2012-02-02 22:52:53

回答

3

顯然,如果從屬對象在容器中定義,則不需要顯式提供具有構造函數參數的Ninject。這與城堡不同。

下面是一個例子。 IGitRepository依賴於IGitAuthor和IGitRepositoryPath。由於兩名受撫養人在我的容器中結合,他們被「神奇地」注入。 Ninject非常聰明,可以看到IGitRepository的構造函數需要它們。所以我只是綁定了IGitRepository,並且放棄了.withConstructorArgument(s)。

Bind<IGitRepository>().To<GitRepository>(); 
     Bind<IGitAuthor>().To<GitAuthor>() 
      .WithConstructorArgument("author", ConfigurationManager.AppSettings["GitAuthor"]) 
      .WithConstructorArgument("email", ConfigurationManager.AppSettings["GitEmail"]); 
     Bind<IGitRepositoryPath>().To<GitRepositoryPath>() 
      .WithConstructorArgument("path",ConfigurationManager.AppSettings["GitServerUri"]); 
相關問題