Close NHibernate session after serialized WCF return object

I have a WCF service with IIS support with single-call behavior. I am using Fluent NH to access data and have encountered the following problem. I cannot close / disconnect the NH session inside the body of the method, because when serialization comes into play, it cannot access the lazy loaded fields. I tried using the approach described in the answer to this question about NHibernate session management in a WCF application , but it also disconnects their session before serialization starts.

You know, can I execute any code in the context of the instance after serialization is complete?

thanks

+4
source share
2 answers

So, I found a compromised solution. I still use the IDispatchMessageInspector implementation from the link above, but I am debugging the extension in a different way.

Here is a snippet of the original implementation

public void BeforeSendReply(ref Message reply, object correlationState) { var extensions = OperationContext.Current.InstanceContext.Extensions.FindAll<UnitOfWorkContextExtension>(); foreach (var extension in extensions) { OperationContext.Current.InstanceContext.Extensions.Remove(extension); } } 

I leave the BeforeSendReply message blank (as happens before serialization), but instead, inside AfterReceiveRequest I can specify an instance of Context.Closing and detach extension in the event handler

 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { instanceContext.Extensions.Add(new UnitOfWorkContextExtension(ServiceLocator.IoC.Retrieve<IUnitOfWorkFactory>().Create())); instanceContext.Closing += DetachExtension; return null; } 
+2
source

I am also interested in the correct solution.

Since NHibernate types cause problems with WCF serialization (even for loaded objects), I recursively look at the object graph and replace all proxies with real objects and .NET base assemblies using reflection. Thus, all objects returned by WCF methods are equal to DTO without reference to NHibernate.

I do this explicitly as part of the WCF method:

 public Document GetDocumentById(int id) { using (var repository = GetRepository()) //Open ISession { var document = repository.GetDocumentById(id); repository.DisconnectObject(document); //Replace proxies return document; //Clean object } //ISession.Dispose } 
0
source

Source: https://habr.com/ru/post/1337754/


All Articles