Connections, where should they be set?

3 posts, 1 answers
  1. Hessner
    Hessner avatar
    189 posts
    Member since:
    Mar 2003

    Posted 12 Nov 2008 Link to this post

    Hi,

    I have a "best practice" question:

    Would like to have global database access in my code behind, without having to open a connection/create an object every time.

    Today in LINQ to SQL, I open a datacontext object i Page_Load and close it again in Page_Unload.

    The Page_Load/Unload are placed in a "master" class that my page inherit from.

    Therefore all my "in-between" code have easy access to the data.

    I know that any time consuming code will hold a connection open, and this is a drawback using this "solution".

    Does OpenAccess support this approach - and what would the Page_Load/Unload code look like?

    Final question,- can you suggest a method, or best practice, as simple as the one I use today?

    Regards,
    Bo Hessner

  2. Answer
    Jan Blessenohl
    Admin
    Jan Blessenohl avatar
    707 posts

    Posted 15 Nov 2008 Link to this post

    Hi Bo,

    The way to work looks good to me. We are caching the session objects anyway so that even if you do not use them, it should not be an overhead.

    In the page load you can just create your business logic instance if you want to have the OpenAccess session in a DAL or create an IObjectScope object directly.

    Add a variable IObjectScope to your master page.
    Retrieve an ObjectScope in page load with:

    - if you have the helper class: scope=ObjectScopeProvider1.GetNewObjectScope();
    - if not: scope=Telerik.OpenAccess.Database.Get("DatabaseConnection1").GetObjectScope();

    In the page Dispose or unload you can just dispose the scope

    The code:
    using System;
    using Telerik.OpenAccess;
    
    public partial class _Default : System.Web.UI.Page 
    {
        private IObjectScope scope;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            //scope = ObjectScopeProvider1.GetNewObjectScope();
            scope = Database.Get("DatabaseConnection1").GetObjectScope();
        }
        public override void Dispose()
        {
            base.Dispose();
            scope.Dispose();
        }
    }
    
    
    I prefer the Dispose place because here is the place where everything should be disposed :)


    Best wishes,
    Jan Blessenohl
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  3. DevCraft banner
  4. Hessner
    Hessner avatar
    189 posts
    Member since:
    Mar 2003

    Posted 15 Nov 2008 Link to this post

    Super Jan!

    Nice to hear, from an expert, that my way of doing things are good - I will replace my Page_Unload with the Dispose event.

    Regards,
    Bo Hessner 
Back to Top