c# – Ninject WithConstructorArgument:没有匹配的绑定可用,并
我对WithConstructorArgument的理解可能是错误的,因为以下内容不起作用:
我有一个服务,让我们调用MyService,其构造函数正在使用多个对象,一个名为testEmail的字符串参数.对于此字符串参数,我添加了以下Ninject绑定: string testEmail = "test@example.com"; kernel.Bind<IMyService>().To<MyService>().WithConstructorArgument("testEmail",testEmail); 但是,当执行以下代码行时,我会遇到异常: var myService = kernel.Get<MyService>(); 这是我得到的例外:
我在这里做错了什么? 更新: 这是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<HttpContextBase>().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,并且由于MyService类型未在您的内核中注册,因此Ninject将其视为自绑定类型. 所以它不会使用你的WithConstructorArgument来解析“testEmail”,因为它只能用于绑定< IMyService>(),这就是为什么你得到异常. 所以如果您已经注册了您的MyService,请执行以下操作: string testEmail = "test@example.com"; kernel.Bind<IMyService>().To<MyService>() .WithConstructorArgument("testEmail",testEmail); 那么你应该通过注册的界面(IMyService)解决它: var myService = kernel.Get<IMyService>(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |