How to manage Session / SessionFactory in WCF / Silverlight

496 views
Skip to first unread message

jcomet

unread,
Sep 29, 2010, 12:14:12 PM9/29/10
to nhusers
I have been successfully using NHibernate in ASP.Net projects by
instantiating a SessionFactory as a static in global.asax, and
binding it via NHibernate.Context.CurrentSessionContext. I am trying
to use the same method in a WCF web service, but I keep getting "An
item with the same key has already been added" exceptions - caused by
the fact that it keeps trying to build a new session factory for each
service call (I think). WCF and silverlight are new to me, and I am
"learning by blog" and am lost. Many posts describe ways to transmit
domain objects down the wire, but I don't want to do that - I am using
DTOs. Many blog posts show injecting ISession in ways that are beyond
my current grasp. I really need a simple silverlight / wcf project
that shows how to manage the ISessionFactory and ISession in WCF
without a lot of window dressing. I am surprised at how much trouble
this is - at least for me. I am hopeful to get some guidance from
this group.

Many thanks in advance.

Trinition

unread,
Sep 30, 2010, 4:15:32 PM9/30/10
to nhusers
First, you can control whether a WCF service object is instantiated
once per call, once per WCF session, etc. by using the ServiceBehavior
attribute. For example, we use a per-call instance (a new instance of
our service object is instantiated for each call):

[ServiceContract]
[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerCall)]
public class MyService : IMyService
...

Second, though, we're using Unity and ServiceLocator. Our no-arg
constructors on our service call to our multi-arg constructors passing
values looked up using ServiceLocator...

public MyService ()
:this(ServiceLocator.Current.GetInstance<IUserTokenFactory>())
{}

public MyService (IUserTokenFactory userTokenFactory)
{
this._userTokenFactory = userTokenFactory;
}

Using this approach, you can register your SessionContextFactory once
in Unity and whenever WCF instantiates your services, your own no-arg
constructor will look up the dependencies for your service using the
ServiceLocator. So SessionFactory can just be one of those things
looked up and passed in.

It's not THE way, but it is A way.

Regards,
Brian.

Fabio Maulo

unread,
Oct 1, 2010, 7:23:37 AM10/1/10
to nhu...@googlegroups.com
http://fabiomaulo.blogspot.com/2009/10/nhibernate-wcf-session-per-call-in.html


--
You received this message because you are subscribed to the Google Groups "nhusers" group.
To post to this group, send email to nhu...@googlegroups.com.
To unsubscribe from this group, send email to nhusers+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nhusers?hl=en.




--
Fabio Maulo

Reply all
Reply to author
Forward
0 new messages