views:

50

answers:

1

Hi all, in my goal to adopt better coding practices I have a few questions in general about automatic handling of code. I have heard different answers both from online and talking with other developers/programmers at my work. I am not sure if I should have split them into 3 questions, but they all seem sort of related:

1) How does .NET handle instances of classes and other code things that take up memory? I recently found out about using the factory pattern for certain things like service classes so that they are only instantiated once in the entire application, but then I was told that '.NET handles a lot of that stuff automatically when mentioning it.'

2) How does Nhibernate's session handle automatic clean-up of un-used things? I've seen some say that it is great at handling things automatically and you should just use a session factory and that's it, no need to close it. But I have also read and seem many examples where people close the hibernate session.

3) How does LINQ's datacontext handle this? Most of the time I never .disposed my datacontext's and the app didn't see to take a performance hit (though I am not running anything super intensively), but it seems like most people recommend disposing of your datacontext after you are done with it. However, I have seen many many code examples where the dispose method is never called. Also in general I found it kind of annoying that you couldn't access even one-deep child related objects after disposing of the datacontext unless you explicity also grabbed them in the query.

Thanks all. I am loving this site so far, I kind of get lost and spend hours just reading things on here. =)

+1  A: 

1) .NET does garbage collection and stuff but it doesn't instantiate things once and provide them to you always, for this purpose you need an IoC Container like Autofac.

2) session by itself doesn't dispose itself off, you need to put it in a using block. But it does take care of other things that it manages.

3) Its always a good idea to dispose of things, particularly unmanaged resources. So, as a rule of thumb put these kind of things in a using block.

Mahesh Velaga
In regards to 2. What does it take care of then? Does it handle the connections to the database and whatnot? If so, what reason would there be to ever dispose of a session if it's not keeping any connections open or storing anything that it should be rid of?
AverageJoe719