好吧,我觉得自己像个白痴。我已经阅读了文档,仍然无法与Ninject合作。
public class ContextAdapter:IDbSetProvider
{
private readonly IContextFactory _contextFactory;
#region Implementation of IDbSetProvider
public ContextAdapter(IContextFactory contextFactory)
{
this._contextFactory = contextFactory;
}
public IDbSet<TEntity> CreateDBSet<TEntity>() where TEntity : class
{
var context = _contextFactory.Create();
return context.Set<TEntity>();
}
#endregion
}
如您所见,我需要为上面的类注入构造函数。嗯,它不是那么顺利。 救命!!在我回到编写perl代码之前。开玩笑! LOL
思想伙伴们?
答案 0 :(得分:2)
您的班级ContextAdapter
未实施IContextFactory
。你有像class Factory : IContextFactory
这样的课吗?这就是你在这里所缺少的。然后你可以绑定它kernel.Bind<IContextFactory>.To<Factory>()
,当你请求一个对象或者它需要履行一个契约时,Ninject会为你创建那个类型。我认为你的困惑来自绑定语法。通常,您不是将参数绑定在一起,而是将接口绑定到具体实现。这是一个简单的例子:
Bind<IEngine>.To<GasEngine>();
Bind<ICar>.To<Sedan>();
class Sedan : ICar
{
public Sedan(IEngine engine) { }
}
// ...
kernel.Get<ICar>(); // get me a new car
当您向Ninject询问ICar
时,它将使用绑定的Sedan
来实现它。 Sedan
在其构造函数中需要IEngine
,Ninject将使用GasEngine
来实现,因为这是绑定的。