在阅读了关于NInject v3的新文档以及如何使用工厂扩展之后,显然我仍然没有完全理解它,因为我的代码在整个过程中都会抛出异常地点...
我得到了这个异常(exception),如果人们愿意的话我可以粘贴整个内容,但我现在会尽量保持简短。
Error activating IDeployEntityContainer No matching bindings are available, and the type is not self-bindable.
这是我的代码... Ninject 绑定(bind)模块类
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>();
...
}
}
工厂接口(interface)
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>();
}
}
Behind the scenes Ninject will create a proxy that implements the specified factory interface and intercept all methods so that the proxy behaves like...
我知道,如果我不需要在工厂内创建对象时做一些特殊/自定义的事情,我就不必自己实际创建实现。
来源:http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
编辑1:
为了确保我为您提供了查看问题所需的所有信息,我添加了 DeployEntityContainer 类/接口(interface)
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)
{
}
}
最佳答案
我最终只是将绑定(bind)更改为普通绑定(bind),
Bind<IMyFactory>().To<MyFactory>().InSingletonScope();
成功了!我的第一个想法是哈哈,但这也有道理。
与 ToFactory()
绑定(bind)它从未使用过我的工厂实现,它只是从定义的接口(interface)生成一个工厂。
现在它使用我的实现。工厂发生了一些变化:从在工厂中更新内核或将其注入(inject)到构造函数中,现在我注入(inject) IResolutionRoot
其中Get<T>();
我的对象。
这里是新代码,仅供说明之用。
class MyNinjectModule : NinjectModule {
public override void Load() {
...
Bind<IDeployEntityFactory>().To<DeployEntityfactory>().InSingletonScope();
Bind<IDeployEntityContainer>().To<DeployEntityContainer>();
...
}
}
public class DeployEntityFactory : IDeployEntityFactory
{
private readonly IResolutionRoot _resolutionRoot;
...
public DeployEntityFactory(..., IResolutionRoot resolutionRoot)
{
...
_resolutionRoot = resolutionRoot;
}
public T GetDeployEntity<T>()
{
return _resolutionRoot.Get<T>();
}
}
如果这不是正确的方法,我希望有人能够阐明它并以正确的方式通知我......我想 @remogloor 会知道这样的事情。 :)
关于c# - NInject 扩展工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207681/