I’m using IDataErrorInfo interface to validate my entities. As long as validation logic is reading metadata from attributes, it is the same for all entities, so I’ve created class
public class DataErrorInfo : IDataErrorInfo
And all entities are derriving from it. Thing is, that I wish to cache reflection info for derived classes to speed up validation, so every entity type should initialize this cache once per running application.
I was thinking to use static readonly field, but found out, that it is initialized with first used entity type’s reflection info, so if there’s entity A and entity B, and entity A is accessed first, entity B will have entity A reflection cache.
In a generic class if you have a static it’s for the closed generic type you can leverage this.
Define your base class as a generic (with a somewhat odd looking but valid constraint)
you then define your derived class like this (notice that the derived class itself is passed as T to the base generic type)
that way any static is scoped to the derived class not the parent class as long as you don’t do as below