开发者

EF DbContext in WCF Services

开发者 https://www.devze.com 2023-04-12 02:28 出处:网络
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 a

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!

0

精彩评论

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

关注公众号