EF DbContext in WCF Services
I am creating an application that uses EF as its data access orm.
My entities are losing its state, causing th开发者_如何学Goat whenever I save a new entity, any objects in relationships are marked as new and try to be inserted as well.
How do I instance my DbContext once per WCF call so I use the same context in the whole service call and prevent it from bieng disposed and let my entities with an inconsistent state?
I used to store the context in the HttpContext when I did web apps, but in WCF there is no such thing as HttpContext.
Where can I store it so is used per call?
Thanks!
You can use HttpContext in WCF.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
I usually cache my DbContext in HttpContext using structuremap's HybridHttpOrThreadLocalScoped:
For<IDbContext>().HybridHttpOrThreadLocalScoped().Use(() => new MyDbContext());
This can be done manually using HttpContext.Current.Items
.
I suppose it could be done differently in pure WCF but it's ok to use aspNetCompatibilityEnabled - imo.
Cheers!
精彩评论