在阅读 NInject v3 上的新文档以及如何使用Factory Extension之后,显然我仍然没有完全得到它,因为我的代码抛出异常到处...
我得到这个例外,如果人们愿意,我可以粘贴整件事,但我会尽量保持简短 .
激活IDeployEntityContainer时出错没有匹配的绑定可用,并且该类型不可自我绑定 .
这是我的代码...... Ninject Bind Module类
class MyNinjectModule : NinjectModule {
public override void Load() {
...
Bind<IDeployEntityFactory>().ToFactory();
Bind<IDeployEntityContainer>().To<DeployEntityContainer>();
...
}
}
使用工厂的类
class DeployController : IDeployController {
private readonly IDeployEntityFactory _entityFactory;
public DeployController(..., IDeployEntityFactory entityFactory) {
...
}
public void Execute() {
...
//I get the Exception on this line...
_entityFactory.GetDeployEntity<IDeployEntityContainer>();
...
}
}
工厂界面
public interface IDeployEntityFactory
{
T GetDeployEntity<T>();
}
工厂实施
public class DeployEntityFactory : IDeployEntityFactory
{
private readonly IResolutionRoot _resolutionRoot;
public DeployEntityFactory(IResolutionRoot resolutionRoot)
{
_resolutionRoot = resolutionRoot;
}
public T GetDeployEntity<T>()
{
return _resolutionRoot.Get<T>();
}
}
在幕后Ninject将创建一个代理,实现指定的工厂接口并拦截所有方法,以便代理行为像...
我知道如果我不需要在工厂内创建对象时做一些特殊/自定义的事情,我就不必实际创建我自己的实现 .
资料来源:http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
EDIT1:
为了确保我留下您需要查看问题的所有信息,我添加了DeployEntityContainer类/接口
public abstract class DeployEntityBase : IDeployEntity
{
...
protected readonly IDeployEntityFactory _entityFactory;
protected DeployEntityBase(..., IDeployEntityFactory entityFactory)
{
...
_entityFactory = entityFactory;
...
}
...
}
public class DeployEntityContainer : DeployEntityBase, IDeployEntityContainer
{
...
public DeployEntityContainer(..., IDeployEntityFactory entityFactory)
: base(..., entityFactory)
{
}
}
1 回答
我最后只是将绑定更改为普通绑定,
它工作了!我的第一个想法是大声笑,但它也是有道理的 .
使用
ToFactory()
绑定它从未使用我的工厂实现,它只是从定义的接口生成一个 .现在它使用我的实现 . 工厂改了一点:从工厂中新建内核或者在构造函数中注入它,现在我注入了
IResolutionRoot
这个对象 .这是新代码,只是为了澄清 .
如果这不是正确的方法,我希望有人可以解释它并以正确的方式通知我......我想@remogloor会知道这样的事情 . :)