这是我的第一个问题,在我试图解决这个问题的过程中,我已经为写什么而苦恼了几天。
我购买了 Mark Seeman 的 .NET 中的依赖注入一书,并一直在尝试遵循该书和 Ninject 网站上的示例来创建抽象工厂类。一般的想法是我有一个包含问题答案列表的表格。答案可以有多种类型,所以我使用工厂来创建相关的答案类型。
我收到错误:
Error activating IAnswerValue
No matching bindings are available, and the type is not self-bindable.
Activation path:
1) Request for IAnswerValue
Suggestions:
1) Ensure that you have defined a binding for IAnswerValue.
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.
我最初尝试使用一个参数,但为了简化这个例子,我把它全部去掉了。错误消息中给出的建议似乎都不适用,工厂类型是绑定的,表单服务也是如此,但 answervalue 显然不是。
这是我的 NinjectWebCommon.cs 中的代码
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.AnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.StringAnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.DateTimeAnswerValue>();
kernel.Bind<IAnswerValueFactory>().ToFactory();
这是答案类定义:
public class Answer
{
readonly IAnswerValueFactory answerValueFactory;
public int Id { get; set; }
public Question Question { get; set; }
public string Type { get; set; }
public Answer(IAnswerValueFactory answerValueFactory)
{
this.answerValueFactory = answerValueFactory;
}
public void GetAnswerValue()
{
var answer = this.answerValueFactory.GetAnswerValue();
}
public List<AnswerItem> PotentialAnswers { get; set; }
}
和答案值:
public interface IAnswerValue
{
AnswerValue GetAnswerValue();
}
public class AnswerValue : IAnswerValue
{
readonly IAnswerValue answerValue;
public AnswerValue() { }
public AnswerValue(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public AnswerValue GetAnswerValue()
{
// this will contain a switch statement to
// determine the type returned but I have
// omitted for this example
return new StringAnswerValue();
}
}
public class StringAnswerValue : AnswerValue
{
public string StringAnswer { get; set; }
}
和工厂:
public class AnswerValueFactory : IAnswerValueFactory
{
readonly IAnswerValue answerValue;
public AnswerValueFactory(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public IAnswerValue GetAnswerValue()
{
return (IAnswerValue)this.answerValue.GetAnswerValue();
}
}
我觉得我已经用尽了我的知识,我只是绕着圈子一遍又一遍地尝试同样的事情。一定有一些很简单的东西我错过了,但我就是看不到它是什么。