如何使用 Ninject 将对象传递给构造函数参数?假设该对象已注册在容器中。
最佳答案
如果依赖对象是在容器中定义的,显然你不需要显式地为 Ninject 提供构造函数参数。这与城堡不同。
这是一个例子。 IGitRepository 依赖于 IGitAuthor 和 IGitRepositoryPath。由于这两个家属被束缚在我的容器中,因此它们被“神奇地”注入(inject)。 Ninject 足够聪明,可以看到 IgitRepository 的构造函数接受它们。所以我只是绑定(bind) 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"]);
关于c# - 如何定义构造函数参数以使用 ninject 获取自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9114350/