Jea*_*amp 20 c# dependency-injection exception-handling ninject ninject-2
我对WithConstructorArgument的理解可能是错误的,因为以下内容不起作用:
我有一个服务,让我们称之为MyService,其构造函数采用多个对象,以及一个名为testEmail的字符串参数.对于此字符串参数,我添加了以下Ninject绑定:
string testEmail = "test@example.com";
kernel.Bind<IMyService>().To<MyService>().WithConstructorArgument("testEmail", testEmail);
Run Code Online (Sandbox Code Playgroud)
但是,在执行以下代码行时,我得到一个异常:
var myService = kernel.Get<MyService>();
Run Code Online (Sandbox Code Playgroud)
这是我得到的例外:
激活字符串时出错没有匹配的绑定可用,并且该类型不可自我绑定.激活路径:
2)将依赖字符串注入到MyService类型的构造函数的参数testEmail中
1)请求MyService建议:
1)确保已为字符串定义了绑定.
2)如果在模块中定义了绑定,请确保已将模块加载到内核中.
3)确保您没有意外创建多个内核.
4)如果使用构造函数参数,请确保参数名称与构造函数参数名称匹配.
5)如果使用自动模块加载,请确保搜索路径和过滤器正确无误.
我在这做错了什么?
更新:
这是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;
}
Run Code Online (Sandbox Code Playgroud)
我有所有构造函数参数类型的标准绑定.只有'string'没有绑定,而HttpContextBase的绑定有点不同:
kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(new HttpContext(new MyHttpRequest("", "", "", null, new StringWriter()))));
Run Code Online (Sandbox Code Playgroud)
和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;
}
}
Run Code Online (Sandbox Code Playgroud)
nem*_*esv 36
声明:
var myService = kernel.Get<MyService>();
Run Code Online (Sandbox Code Playgroud)
您正在尝试解析MyService,因为MyService类型未在您的内核中注册,Ninject会将其视为自绑定类型.
因此它不会使用你WithConstructorArgument来解决"testEmail"它,因为它只会被用于Bind<IMyService>()这就是你得到异常的原因.
因此,如果您已经注册MyService了:
string testEmail = "test@example.com";
kernel.Bind<IMyService>().To<MyService>()
.WithConstructorArgument("testEmail", testEmail);
Run Code Online (Sandbox Code Playgroud)
然后你应该通过注册的接口(IMyService)来解决它:
var myService = kernel.Get<IMyService>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39382 次 |
| 最近记录: |