I write a layered .NET 4.0 application. The data layer is implemented using the Entity Framework, and there are repositories that provide the entity instances to the caller, i.e., the business layer. When the entity framework is asked for a certain entity twice (e.g. by key), it will return the same instance, so changes I make to the entity will be reflected in other places the entity is used. It is not really a caching functionality though, since there is no expiration policy, and performance does not seem to be improved much since the entity framework will still query the database, at least in many cases. The point is simply to make sure that there is only one instance (per context) of each entity.
In the business layer, the entities are mapped to business objects which may differ in structure from the entities. Again, like the repositories in the data layer, there are centralized points of access to obtain instances of the business objects. My goal now is, to have the same functionality that the entity framework provides, meaning “always returning the same instance for a certain object”, in the business layer. I would like to make sure, that every access to a certain business object anywhere in the application will work on the same instance.
BEGIN EDIT
Context awareness is important! Similarly to the entity framework, the uniqueness of each business object instance should be provided on a per context base, not strictly over the whole application. In the business layer there is also the notion of a context, and each context should have its own instance of each business object. This instance should be reused everywhere the context is used.
Also I am looking for a solution, that needn’t be implemented for every single business object class. There are potentially hundreds of them. I would prefer a solution in framework code, that is as transparent as possible to someone implementing a repository. The entity framework itself also doesn’t know about specific entity types, still the entity framework is capable of providing this functionality transparent to an entity model developer.
END EDIT
My questions are:
- Is there a name for this “only one instance per object” behavior? What would be the Google search term?
- Are there references, guidelines or best practices, or is there even a design pattern dealing with this issue?
- Are there classes in .NET that are helpful for writing such functionality, or even provide it completely?
Thanks and regards,
Peter.
Yes it has a name. It is called Identity Map pattern and generally it is just a dictionary of object key / object pairs.