开发者

Unity not honoring TransientLifetimeManager?

I have the following scenario:

A WCF service solution that contains a service implementation layer, business layer and data layer. The WCF implementation layer depends on the business layer and the business layer on the data layer. Each layer receives it's dependencies via constructor injection. We've wired this all together using Unity. We have a custom WCF service host/factor/behavior/instance provider that calls into our Unity container to resolve the WCF service to use and it's various dependencies.

It's working great...almost.

We're using EntityFramework code first in our data layer. What we're seeing is that a new DbContext class is created on the initial call into WCF, but that class is reused on subsequent calls into the service. This becomes a problem of course when our service is serving multiple calls that are accessing the database concurrently. I was able to prove out that the DbContext class is in fact being reused by placing some trace statements in the DbContext class' constructor. I went further up the chain and places similar trace statements in the business layer implementation constructor and found that this is also only being called once. In fact, it appears that only the WCF service implementation is being constructed on each service call and that the data and business layers are behaving as singletons.

From what I've read, it sounds like the default behavior when using RegisterType with Unity is to use the TransientLifetimeManager and that this implies a new instance will be created on every call to Resolve. Since it didn't appear that this default behavior was working correctly, we tried explicitly setting the lifetime manager as TransientLifetimeManager, however we're still seeing our business and data layers behaving as singletons.

Any ideas on what I need to do to get our WCF dependencies to behave as singletons?

Update: Still no success. I tried using the PerResolveLifetimeManager, however that did not solve the problem. As a temporary work around, I refactored my code so that it's injecting a factory into my data layer. The factory provides DbContext instances, so I'm able t开发者_如何学Goo ensure that each call into my data layer is using a new DbContext. This is working ok for now, but I'd like to resolve whatever issue is causing Unity to hold onto and re-use instances after they're created.


The way we use:

  1. We register our DbContext with HierarchicalLifetimeManager (and other services).
  2. In WCF instance provide we create new child contriner and resolve service from this (child) container.
  3. Mark service with [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

So, the magic of HierarchicalLifetimeManager gives us new instance of service and all related data for every request.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜