Nhibernate how many sessions




















Could not load tags. Latest commit. Git stats 27 commits. Failed to load latest commit information. View code. Sessions NHibernate. You can then use method chaining to call any of the following methods: WithCachedConfiguration ForSingleSessionFactory getConfiguration.

WithCachedConfiguration Assembly. WithCachedConfiguration configurationCache , Assembly. RegisterSessionFactory " TodoItems ". WithBackgroundInitialization BackgroundInitialization. WithCachedConfiguration typeof TodoItem. CreateLazySessions ;. Second, once you save an entity, you want to ensure that every form that also displays this entity is updated with the new values.

The first item of business is actually fairly easy to handle. Figure 5 shows the code driving this screen. You get the entity from the database in the Initialize id method, and you update it in the OnSave method.

Notice that you do so in two separate transactions, instead of keeping a transaction alive for a long period of time. On the face of it, that looks like a waste.

Why should you load the same action several times? In actuality, having this separation between the forms will simplify the application considerably.

Consider what would happen if you shared the entity instances across the board. In that situation, you would find yourself with a problem in any conceivable edit scenario. Consider what would happen if you were to display an entity in two forms that allow editing that entity. That may be an editable grid and a detailed edit form, for example. If you make a change to the entity in the grid, open the detailed edit form and then save it, what would happen to the change you made on the editable grid?

Sharing an entity instance also makes it much more difficult to do things like cancel an edit form and have all the unsaved changes go away.

Those problems simply do not exist when you use an entity instance per form, which is a good thing, as this is more or less mandatory when you use a session per form approach. Instead of having a single instance of the entity in the application, you may have many, but the user would still like to see the entity once properly saved updated on all the forms that show that entity. In my example I do so explicitly.

Whenever I save an entity, I publish an event saying that I did so, and on which entity. NET event. NET event requires a class to subscribe to it directly. Just trying to manage that would be a nightmare. The EventPublisher is a publish-subscribe mechanism that I use to decouple a publisher from its subscriber. The only commonality between them is the EventPublisher class. I use the event type ActionUpdated in Figure 5 to decide who to tell about the event. When I update a to-do action, I would like to show the updated values in the main form, which shows a grid of to-do actions.

Here is the relevant code from that form presenter:. Now, whenever that event is raised, I will simply refresh the current page by calling LoadPage, which you are already familiar with. This is actually a fairly lazy implementation. A more complex and efficient implementation would only refresh the grid data if the updated entity is shown on that page.

The main advantage of using the publish-subscribe mechanism in this manner is decoupling the publisher and subscribers. The idea of event publishing and publish-subscribe is a cornerstone in building loosely coupled user interfaces, and is covered extensively in the Composite Application Guidance msdn. There is another case worth considering: What would happen if you have two edit forms to the same entity open at the same time? How can you get the new values from the database and show them to the user?

This explicit model of refreshing the entity from the database also gives you the chance to make decisions about what should happen now.

Should you update automatically, erasing all the user changes? Should you ask the user? Try to silently merge the changes? Those are all decisions that you now have the chance to deal with in a straightforward manner. In most cases, however, I find that simply refreshing the entity is quite enough, because you generally do not allow updating of a single entity in parallel at least not by a single user. While this entity refresh code will indeed update the values of the entity instance, how are you going to make the UI respond to this change?

You have data bound the entity values to the form fields, but you need some way of telling the UI that those values have changed. The Microsoft. An object that implements this interface should raise the PropertyChanged event with the name of the property that was changed. One of the requirements of NHibernate is that you make all properties and methods on your classes virtual. NHibernate requires this to handle lazy loading concerns properly, but you can take advantage of this requirement for other reasons.

One thing you can do is take advantage of the virtual keyword to inject your own behavior into the mix. In essence, you take a class and add additional behaviors to this class at runtime. The entire implementation of the class is about 40 lines, not terribly complex. What it does is take a type and produce an instance of this type that also fully implements the INotifyPropertyChanged contract. In other words, the following test will work:. Given that, all you have to do now is make use of the DataBindingFactory whenever you create a new class in the presenters.

The main advantage that you gain from such a system is that now, if you would like to make use of the NHibernate domain model in a non-presentation context, you can simply not make use of the DataBindingFactory, and you get a domain model completely free from presentation concerns.

While you can create new instances of entities using the DataBindingFactory, a lot of the time you will have to deal with instances that were created by NHibernate. But before you despair, you can make use of one of the most useful extension points with NHibernate, the Interceptor. One of the functionalities that the Interceptor allows you to take over is creating new instances of entities. Figure 6 shows an Interceptor that creates instances of entities using the DataBindingFactory.

You override the Instantiate method and handle the case where we get an entity with a type that you recognize. You then proceed to create an instance of the class and set its identifier property.

You also need to teach NHibernate how to understand what type an instance created via DataBindingFactory belongs to, which you do in the GetEntityName method of the intercepter. The only thing left now is to set up NHibernate with the new Interceptor. The following is taken from the BootStrapper class, responsible for setting up the application:.

For now, ignore the configuration semantics—I will address that in a bit. I suspect that this may be a problem. How many open sessions can I have in NHibernate? Should I have only a small number, or can I have as many open sessions as I need? It depends how long you keep your sessions open for and what you do with them.

The session itself is pretty lightweight and doesn't necessarily open a connection to the database. However I think that having 50 open sessions for 1 form is not the best design.

I would suggest using a session as a "unit of work" in that when you want to do something such as present some data, or update some data, or list a bunch of entities , you open the session, do your work, and then dispose of the session. This can cause some issues with lazy loading and data-binding, but you can work around those by fetching the required associations. You can reconnect entities that you have loaded in one session into another by using session.

Lock entity, LockMode. None , so you don't need to have the session open between user interactions. Stack Overflow for Teams — Collaborate and share knowledge with a private group.

Abstracts application from the concrete vendor-specific implementations of DbConnection and DbCommand. Optional An interface encapsulating differences between ADO. NET features. Optional A factory for ITransaction instances. NET directly. An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context. The NHibernate ISession object is the persistence context:. The instance is not, and has never been associated with any persistence context.

It has no persistent identity primary key value. The instance is currently associated with a persistence context. It has a persistent identity primary key value and, perhaps, a corresponding row in the database.

For a particular persistence context, NHibernate guarantees that persistent identity is equivalent to CLR identity in-memory location of the object. The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database. For detached instances, NHibernate makes no guarantees about the relationship between persistent identity and CLR identity.

Most applications using NHibernate need some form of "contextual" sessions, where a given session is in effect throughout the scope of a given context. However, across applications the definition of what constitutes a context is typically different; and different contexts define different scopes to the notion of current.

Starting with version 1. GetCurrentSession method. The processing behind ISessionFactory.



0コメント

  • 1000 / 1000