开发者

Ninject not creating a new instance with constructor arguments in WCF

Here is the scenario. I have a WCF service, when this service is called it passes control to an instance of another class (created via Ninject). In that class I need to do some work, specifically with Entity Framework and repositories. To cut a long story short, I have the following binding declared.

Bind<IGenericProductRepository>()
    .To<GenericProductRepository>()
    .WithConstructorArgument( "context", new StagingDataContext());

When I want to use this repository I have the following.

using (var genericProductRepository = IoC.Resolve<IGenericProductRepository>())

The problem is, that I onl开发者_JAVA百科y get a new instance of genericProductRepository if it's a brand new request, if the method is called multiple times in the same request I get an error stating that the context (the EF context) is already disposed, this is because it seems like I am getting the same instance back that was already disposed in the using statement. To explain it another way, using the Microsoft WCF Test Client, if I invoke it the first time, the code runs fine, if I push the invoke button again (without restarting the test client, i.e. the same request) then it throws this error about it being disposed already.

I have tried to play around with the various "scopes" that come with Ninject, but clearly I am missing something.

So my basic question is, how do I get a new repository whenever it hits that line, instead of using the same one ? Help would be greatly appreciated, I'm really trying to push for my company to adopt Ninject and drop Spring.


Look at your binding again. Even without any knowledge about Ninject you should notice that the instance of your context is created exactly once at the time the binding is defined. But what you want is have a new context on every resolve. Best it is done by not using WithConstructorArgument and let Ninject create the instance. Therefore you have to define a additional binding for the type of context. If this is not possible for some reason you have to use the lazy version of WithConstructorArgument

WithConstructorArgument("context", ctx => new StagingDataContext())

Furthermore, you might want to try The WCF extension for Ninject: https://github.com/ninject/ninject.extensions.wcf

That way you can get rid of the ServiceLocator like usage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜