Ninject WithConstructorArgument:没有匹配的绑定可用,并且该类型不可自绑定
我对WithConstructorArgument的理解可能是错误的,因为以下内容不起作用:
我有一个服务,让我们称之为MyService,其构造函数采用多个对象,以及一个名为testEmail的字符串参数。 对于此字符串参数,我添加了以下Ninject绑定:
string testEmail = "test@example.com"; kernel.Bind().To().WithConstructorArgument("testEmail", testEmail);
但是,在执行以下代码行时,我得到一个exception:
var myService = kernel.Get();
这是我得到的例外:
激活字符串时出错没有匹配的绑定可用,并且该类型不可自我绑定。 激活路径:
2)将依赖字符串注入到MyService类型的构造函数的参数testEmail中
1)请求MyService建议:
1)确保已为字符串定义了绑定。
2)如果在模块中定义了绑定,请确保已将模块加载到内核中。
3)确保您没有意外创建多个内核。
4)如果使用构造函数参数,请确保参数名称与构造函数参数名称匹配。
5)如果使用自动模块加载,请确保搜索路径和filter正确无误。
我在这做错了什么?
更新 :
这是MyService构造函数:
[Ninject.Inject] public MyService(IMyRepository myRepository, IMyEventService myEventService, IUnitOfWork unitOfWork, ILoggingService log, IEmailService emailService, IConfigurationManager config, HttpContextBase httpContext, string testEmail) { this.myRepository = myRepository; this.myEventService = myEventService; this.unitOfWork = unitOfWork; this.log = log; this.emailService = emailService; this.config = config; this.httpContext = httpContext; this.testEmail = testEmail; }
我有所有构造函数参数类型的标准绑定。 只有’string’没有绑定,而HttpContextBase的绑定有点不同:
kernel.Bind().ToMethod(context => new HttpContextWrapper(new HttpContext(new MyHttpRequest("", "", "", null, new StringWriter()))));
和MyHttpRequest定义如下:
public class MyHttpRequest : SimpleWorkerRequest { public string UserHostAddress; public string RawUrl; public MyHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output) : base(appVirtualDir, appPhysicalDir, page, query, output) { this.UserHostAddress = "127.0.0.1"; this.RawUrl = null; } }
随着声明:
var myService = kernel.Get();
您正在尝试解析MyService
并且因为MyService
类型未在您的内核中注册,Ninject会将其视为自绑定类型。
所以它不会使用你的WithConstructorArgument
来解析"testEmail"
因为它只会与Bind
,这就是你获得exception的原因。
因此,如果您已注册MyService
:
string testEmail = "test@example.com"; kernel.Bind().To() .WithConstructorArgument("testEmail", testEmail);
然后你应该通过注册的接口( IMyService
)来解决它:
var myService = kernel.Get();
虽然nemesv有正确的响应,我遇到了同样的错误,我的解决方案是我/ bin中的恶意DLL。 我重构并删除/移动了一些仍然存在于我的旧DLL中的类。 解决方案 – 删除旧的DLL。