【问题标题】:Ninject + WCF IssueNinject + WCF 问题
【发布时间】:2011-07-12 12:26:20
【问题描述】:

我正在尝试将 Ninject 与我的 WCF 服务一起使用。我正在使用 Ninject 2.2.1.4 和 Ninject.Extensions.Wcf 2.2.0.4。我确保 Ninject 正常工作的单元测试因 ArgumentNullException 而失败;参数根:null。

这是我的代码:

  //A couple of classes to setup ninject and its bindings
 public class NinjectBindings : NinjectModule
{
    public override void Load()
    {
        Bind<IEmployeeRepository>().To<SqlEmployeeRepository>().InSingletonScope();
    }

}

 public class Global : NinjectWcfApplication
{       
    protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new NinjectBindings());
        return kernel;
    }
}

//Test method that fails with ArgumentNullException
  [TestMethod]
    public void Should_Be_Able_To_Get_Employee_Service_From_Ninject()
    {
        Global globalService = new Global();

        var kernel = globalService.Kernel;

        EmployeeService employeeService = kernel.Get<EmployeeService>();

        Assert.IsNotNull(employeeService);
    }

【问题讨论】:

    标签: asp.net-mvc wcf unit-testing ninject


    【解决方案1】:

    创建Global 后,您必须像IIS 那样调用Application_Start()Init() 来正确初始化它。在此之后,您的集成测试应该运行。

    但请注意,实际上kernel.Get 不会像您在测试中那样直接触发。服务的创建要复杂得多。

    【讨论】:

    • Global 只是一个类,而不是 global.asax...不确定这是否会导致问题(我是 Web 服务的菜鸟)。你能提供一些代码来帮助我纠正并使我的单元测试通过吗?我不是很清楚,谢谢。
    • Global 派生自 NinjectWcfApplication,它是一个 HttpApplication 没有初始化它不能被使用。见github.com/ninject/ninject.extensions.wcf/tree/Maintenance_2.2/…
    【解决方案2】:

    当使用 Ninject.Wcf 时,您的 Global 不会像您所做的那样得到 newd - 您告诉 WCF 创建 Global 的工厂是 ~NinjectWcfHostFactory,这会触发 CreateKernel(),这在你的上下文。

    该示例显示了工厂的覆盖(在.svc 文件中的服务声明的属性中)。

    【讨论】:

    • 感谢您的回复。我对 Web 服务和 ninject 有点陌生。您能否发布一些代码来帮助我更好地理解如何纠正我的问题?
    • @Beavis:不想去追查源头,但幸运的是@Remo Gloor 做到了。今天还有另一个人问了几乎相同的问题——去看看答案。只是想指出a)你正在做一个错误的假设b)ninject github上有显示正确方法的样本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    相关资源
    最近更新 更多