所以,我已经挖了很长时间才找到答案而没有运气。
我做错了什么?
Ninject通过以下消息抛出异常:
Error activating IModelRepository{User}
No matching bindings are available, and the type is not self-bindable.
这是我的代码:
我有一个通用接口:
public interface IModelRepository<T> where T: IModel
{
//interface stuff here
}
具体课程是:
public UserRepository : IModelRepository<User>
{
public UserRepository(IDocumentStore documentStore, string databaseName)
{
//constructor code here
}
}
Ninject模块Load():
public override void Load()
{
string databaseName = Properties.Settings.Default.DefaultDatabaseName;
Bind<IModelRepository<User>>()
.To<UserRepository>()
.WithConstructorArgument("documentStore", Kernel.Get<IDocumentStore>())
.WithConstructorArgument("databaseName", databaseName);
}
Ninject实例化(这是异常发生的地方):
Kernel = new Ninject.StandardKernel(new DIModules.ModelRepositoryModule()
,new DIModules.DocumentStoreModule());
这是完整的堆栈跟踪:
at Ninject.KernelBase.Resolve(IRequest request) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 359
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 263
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37
at xl.view.DIModules.DataStoreModule.Load() in c:\Users\Michael\Google Drive\Projects\Windows\xl\xl.view\DIModules\DataStoreModule.cs:line 18
at Ninject.Modules.NinjectModule.OnLoad(IKernel kernel) in c:\Projects\Ninject\ninject\src\Ninject\Modules\NinjectModule.cs:line 85
at Ninject.KernelBase.Load(IEnumerable`1 m) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 217
at Ninject.KernelBase..ctor(IComponentContainer components, INinjectSettings settings, INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 100
at Ninject.KernelBase..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 57
at Ninject.StandardKernel..ctor(INinjectModule[] modules) in c:\Projects\Ninject\ninject\src\Ninject\StandardKernel.cs:line 46
at xl.view.Program.InitializeApplication() in c:\Projects\Windows\xl\xl.view\Program.cs:line 53
at xl.view.Program.Main() in c:\Windows\xl\xl.view\Program.cs:line 28
答案 0 :(得分:1)
尝试更改模块的顺序,似乎顺序很重要,因为IModelRepository<User>
在绑定它们之前不了解IModel
和User
:
Kernel = new Ninject.StandardKernel(
new DIModules.DocumentStoreModule(),
new DIModules.ModelRepositoryModule());
这适用于我,这里有完整的示例:http://pastebin.com/2TjBqAwc
答案 1 :(得分:1)
.WithConstructorArgument("documentStore", Kernel.Get<IDocumentStore>())
您可能希望将其更改为 ctx=>
Kernel.Get<IDocumentStore>()
。您调用它的方式是,您在模块Load()
期间创建对象 - 这不应该是casse - Moduel Load()
方法只应该Bind()
。
此外,没有设备的开发环境,但很确定应该有一种方法让默认配置负责将ctor param绑定到DI将解决的任何内容。
(如果以上都没有意义,那么你肯定需要提供比你更完整的堆栈跟踪)