Reputation: 4702
Using VB.NET on this one, in ASP.NET Web Forms.
I have a property that reads a list from a database over the entity framework, as follows:
Public ReadOnly Property MyProperty As List(Of MyType)
Get
Using service As New MyDatabaseService
Return service.GetMyTypeList()
End Using
End Get
End Property
Because this service requires a round-trip to the database, I'd like to cache the results for future accesses during the same page lifecycle (no ViewState needed). I know this can be done as follows:
Private Property _myProperty As List(Of MyType)
Public ReadOnly Property MyProperty As List(Of MyType)
Get
If _myProperty Is Nothing Then
Using service As New MyDatabaseService
_myProperty = service.GetMyTypeList()
End Using
End If
Return _myProperty
End Get
End Property
Now for the question: is there any way to utilize caching via an attribute, to "automatically" cache the output of this property, without having to explicitly declare, test for, and set the cached object as shown?
Upvotes: 3
Views: 277
Reputation: 44906
The answer is sort of, but you will need to use Aspect Oriented Programming techniques in order to achieve this. Castle Windsor or PostSharp are two excellent .net frameworks that can help get you there, but this is not a light subject by any means.
Basically AOP involves wrapping up common boilerplate functionality into aspects that can be used to decorate code, leaving only the essence of what you want. This can be done dynamically at runtime as Castle does, or at compile time by IL weaving (dynamically compiling the new code into your assembly).
Each approach has its strengths and weaknesses, but I urge you to research the topic as it spans further than just caching. Many common tasks such as exception handling and logging can easily be refactored into aspects to make your code extra clean.
Upvotes: 1