Search code examples
.netdatabasemultithreadingnhibernatefluent-nhibernate

Is GeneratedBy.Increment() thread-safe within a single SessionFactory?


My application uses

Id(x => x.Id).GeneratedBy.Increment();

for generating primary keys. I have read a few articles about Increment and I am quite worried now: all those articles say Increment is dangerous when used in cluster. However, have no cluster, it is a common web application with a single SessionFactory instance. There are concurrent threads, though, all sharing the same SessionFactory.

Should I be worried? What object provides new created instances with their primary key values? Is it the thread-safe SessionFactory, or the not-safe Session?


Solution

  • Looking at the source, the Generate() method of the IncrementGenerator class is decorated with the MethodImpl attribute and the MethodImplOptions.Synchronized option. This suggests that access to the method is synchronised and, therefore, thread-safe.