【问题标题】:NamedLikeFactoryMethod in Ninject Extensions Factory working in non-compliance with documentationNinject Extensions Factory 中的 NamedLikeFactoryMethod 不符合文档要求
【发布时间】:2012-07-19 09:31:19
【问题描述】:

我的简单示例有一个小问题。

我有简单的工厂接口:

public interface ICameraFactory
{
  ICameraController GetNikonCamera();
  ICameraController GetCanonCamera();
}

我将它绑定为工厂:

IKernel kernel = new StandardKernel();
kernel.Bind<ICameraFactory>().ToFactory();

当我尝试转换时:

kernel.Bind<ICameraController>().To<NikonCameraController>()
.Named("NikonCamera");

到:

kernel.Bind<ICameraController>().To<NikonCameraController>()
.NamedLikeFactoryMethod<ICameraFactory>(f => f.GetNikonCamera());

它不编译。

比如这段代码是编译的(但是很糟糕):

kernel.Bind<ICameraController>()
.ToMethod<ICameraController>(c=>new NikonCameraController())
.NamedLikeFactoryMethod<ICameraController, ICameraFactory>(f => f.GetNikonCamera());

我做错了什么? Ninject 3.0.1.10 Ninject.Extension.Factory 3.0.1.0

编译错误:https://dl.dropbox.com/u/21806986/Screenshots/shot_19072012_133454.png

【问题讨论】:

    标签: dependency-injection ninject ninject-extensions


    【解决方案1】:

    你可以使用:

    this.kernel.Bind<ICameraController>()
               .To<NikonCameraController>()
               .NamedLikeFactoryMethod((ICameraFactory f) => f.GetNikonCamera());
    

    【讨论】:

    • 谢谢你的回答,但我试过了,它没有用。我有这样的编译错误:dl.dropbox.com/0/view/23e0vwi9fnjtx5b/Apps/CloudShot/…
    • 但它的工作:kernel.Bind&lt;ICameraController&gt;().ToMethod&lt;ICameraController&gt;(x =&gt; new NikonCameraController()).NamedLikeFactoryMethod&lt;ICameraController, ICameraFactory&gt;(f =&gt; f.GetCanonEOSCamera()); 哪里:public class NikonCameraController : ICameraController { //Some implementation }
    • Sry 记错了。第一个通用参数是实现类型(NikonCameraController)而不是接口类型。但是没有这种类型有更好的语法。查看更新的答案。
    • 感谢您的回答和 Extension.Factory!它工作正常。我认为可以将其添加到 wiki(如最佳实践)。
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2011-07-11
    • 2021-01-20
    相关资源
    最近更新 更多