Wednesday, June 29, 2005

[Opf3] Recommended pattern: ObjectContextFactory

For creating instances of the ObjectContext class in your application I highly recommend to create some factory that creates them for you. A factory is a class that contains one method that returns an initialized instance of a certain class.

An example of such a class is found in the Opf3.Utilities. That class requires creating your own ObjectContextFactory (by inheriting from the current one in Opf3.Utilities) and overriding one method of that base class (the name of the method is CreateObjectContext). In the overriden method you have to create an instance of the ObjectContext and return that instance. The instance of the ObjectContext is retrieved by calling the method "GetObjectContext" (see example).


MyObjectContextFactory fact = // Get the ObjectContextFactory from some static class.
// Get an instance of the ObjectContext.
ObjectContext context = fact.GetObjectContext();

// Get all user from the storage.
ObjectSet<User> os = context.GetObjectSet<User>();


The ObjectContextFactory that comes with the utilities creates a new instance of an ObjectContext for each different thread requesting an ObjectContext. This means that in a multithreaded environment each thread has it's own instance of the ObjectContext. If the thread does no longer exist the instance is removed automatically.

If you need any other behaviour you can use the ObjectContextFactory of the utilities as a template or adopt it to work in your scenario(s).

0 Comments:

Post a Comment

<< Home