在阅读了关于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/
编辑1:
只是为了确保我为您提供了查看问题所需的所有信息,我正在添加 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)
{
}
}