tips for embedding db4o in ASP.NET
to use db4o effectively in ASP.NET, place all your business classes in a separate class library project and then refer to that project in your ASP.NET project. avoid putting class definitions in the App_Code folder of your project since this will be compiled on the fly and given a different namespace every time it is recompiled. this means that instances of the class Foo, which was compiled yesterday, will have a different namespace from the the instances of the class Foo that is compiled today. db4o will treat instances of class Foo that was stored yesterday and today as belonging to different types since their namespaces are different.
it is important to keep the db4o client open during a particular session and just close the client when that session ends. the best way to do this is to use an HttpModule as illustrated by the class below.
internal class Db4oHttpModule : IHttpModule
{
const string KEY_DB4O = "db4o"; // appSettings key
const string KEY_CLIENT = "db4oClient";
private static ObjectServer server = null;
internal static ObjectContainer Client
{
get
{
HttpContext context = HttpContext.Current;
ObjectContainer client = context.Items[KEY_CLIENT] as ObjectContainer;
if (client == null)
{
client = Server.OpenClient();
context.Items[KEY_CLIENT] = client;
}
return client;
}
}
private static ObjectServer Server
{
get
{
if (server == null)
{
string yapFilePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[KEY_DB4O]);
server = Db4o.OpenServer(yapFilePath,0);
}
return server;
}
}
private void OnApplicationEndRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
ObjectContainer client = context.Items[KEY_CLIENT] as ObjectContainer;
if (client != null)
{
client.Close();
}
client = null;
context.Items[KEY_CLIENT] = null;
}
public void Init(HttpApplication application)
{
application.EndRequest += new EventHandler(OnApplicationEndRequest);
}
public void Dispose()
{
if (server != null)
{
server.Close();
}
server = null;
}
}