我在項目中使用Ninject作爲IoC容器。我有以下類:基於約定的構造函數字符串參數與Ninject的綁定
public class SomeRepository:ISomeRepository
{
public SomeRepository(string someDatabaseConnectionString)
{
// some code here..
}
}
在我的應用程序設置文件中我有連接字符串名爲「someDatabase」。默認情況下,應該以注入此連接字符串到構造函數中添加以下配置:
kernel.Bind<ISomeRepository>()
.To<SomeRepository>()
.WithConstructorArgument("someDatabaseConnectionString", connString);
,但我想實現這樣的字符串的常規基結合。名稱以「ConnectionString」結尾的字符串類型的所有構造函數參數的值應該從應用程序的connectionStrings配置節中取出並自動注入。我也想爲appSettings部分實現類似的約定。這種方法在Mark Seeman的"Primitive Dependencies"文章(「原語的約定」部分)中有更詳細的描述。示例中使用了Castle Windsor容器。
是否可以使用Ninject來實現這樣的約定,以及最好的方法是什麼?我已經嘗試ninject.extensions.conventions,但似乎它沒有這樣的功能,是嗎?
你可以使用ConfigurationManager.AppSettings [「someDatabaseConnectionString」]? – Ben
當前我正在使用ConfigurationManager.AppSettings [「someDatabaseConnectionString」]。但是想象一下,你有20個或更多的依賴於連接字符串的類。我不想爲每個這些類寫特定的規則,我想自動注入依賴關係。 –