c# – Ninject WithConstructorArgument:没有匹配的绑定可用,并且类型不是自绑定的

前端之家收集整理的这篇文章主要介绍了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>();

这是我得到的例外:

Error activating string No matching bindings are available,and the
type is not self-bindable. Activation path:
2) Injection of
dependency string into parameter testEmail of constructor of type
MyService
1) Request for MyService

Suggestions:
1) Ensure that you have defined a binding for string.
2) If the binding was defined in a module,ensure that the module has
been loaded into the kernel.
3) Ensure you have not accidentally
created more than one kernel.
4) If you are using constructor
arguments,ensure that the parameter name matches the constructors
parameter name.
5) If you are using automatic module loading,ensure
the search path and filters are correct.

我在这里做错了什么?

更新:

这是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>();

猜你在找的C#相关文章