NHibernate & WCF in version 3.0
I've just started a new project which requires a WCF service to handle a distributed environment. I'm still trying to find the best way to implement things.
I want to use NHibernate, but I've seen a few different ways to address the serialization. Is this handled in 3.0? I noticed wcf_context insi开发者_运维问答de the truck :D
If it isn't handled could someone point me in the right direction?
Thanks everyone
Typically if you're going to return data from a service, you'll want to return a class specific for the purpose of the service, containing what is pertinent to that service call, a DTO (Data transfer object) or DataContract in the WCF world.
One tool that is particularly helpful for mapping between entities and DTO's is AutoMapper. Whether you use AutoMapper or just "left-right" coding, this will prevent the lazy loading / delayed execution issue because doing the mapping will cause the execution to occur.
There are a number of reasons why it might not be a good idea to return an entity from a service, here are a few (there are varying opinions on most of this)
- Depending on your persistence (in your case nhib) you may have behavior (delayed execution) or state attached to your entities which won't execute correctly in another app or server
- Returning entity results in a service layer often results in calls that are very CRUD-like, results in a very chatty service layer, and very un-SOA
- Different calls might require more or less data than just what's an entity, a DTO gives you the ability to wrap up exactly what you need, and nothing you don't.
- If you're trying to build a reusable service layer, you should not assume your clients have access to your entity or domain logic other than what's in your service. they could be written in another app, another language, etc. If your entities are what you'r using to move data around, you'll be inclined to forget this.
You can't pass Lazy loaded object using WCF.
there are some ways around it, but there is a bug which will be fixed in the next WCF version (coming soon, apr 2010)
Other than that, they leave happily together, as long as you define the objects with the rigth DataContract.
There is also an issue in serialization of Lists - You need to generate the proxy using svcutil with a certain flag or bad things happens (the lists becomes arrays and you can't add more items) (unless you use a certain kind of list that both WCF and NHibernate agrees) - look that up (Nhiberate and WCF Lists) -
精彩评论