2

在阅读了关于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)
    {
    }
}
4

1 回答 1

2

我最终只是将绑定更改为普通绑定,

Bind<IMyFactory>().To<MyFactory>().InSingletonScope();

它奏效了!我的第一个想法是大声笑,但这也很有意义。

使用ToFactory()绑定它从未使用过我的工厂实现,它只是从定义的接口生成一个。

现在它使用我的实现。工厂有点改变:从在工厂中更新内核或在构造函数中注入它,现在我注入IResolutionRootGet<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 会知道这样的事情。:)

于 2012-06-27T10:19:14.517 回答