2011-07-12 70 views
0

我正在尝试将Ninject与我的WCF服务一起使用。我正在使用Ninject 2.2.1.4和Ninject.Extensions.Wcf 2.2.0.4。我的单元测试,以确保Ninject正常工作失败,带有ArgumentNullException;参数root:null。Ninject + WCF问题

这里是我的代码:

//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); 
    } 

回答

0

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

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

+0

全球只是一个类,而不是global.asax ...不知道这是否导致问题(我是一个Web服务noob)。你能提供一些代码来帮助我纠正并让我的单元测试通过吗?我不完全清楚,谢谢。 – Mike

+0

全局派生自NinjectWcfApplication,它是一个无法使用的初始化的HttpApplication。请参阅https://github.com/ninject/ninject.extensions.wcf/tree/Maintenance_2.2/src –

0

使用Ninject.Wcf,你Global犯规得到new d为你做 - 你告诉WCF,该工厂用于创建全球的〜NinjectWcfHostFactory,这会触发CreateKernel()这是不在你的情况下发生。

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

+0

感谢您的回复。我对Web服务和ninject有点新。你可以发布一些代码,以帮助我更好地了解如何纠正我的错误? – Mike

+0

@Beavis:不打算追逐来源,但幸运的是@Remo Gloor做到了。还有一个人今天也问了几乎相同的问题 - 请看这个问题的答案。只是想指出:a)你正在做假设b)ninject github上有示例显示正确的喜好。 –