Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created March 25, 2015 16:38
Show Gist options
  • Save DominicFinn/78fd6a5e825f2945bbc8 to your computer and use it in GitHub Desktop.
Save DominicFinn/78fd6a5e825f2945bbc8 to your computer and use it in GitHub Desktop.
Generic example in VB.NET showing how one database can handle multiple types.
Public MustInherit Class ReadModel
Public Property Id As Guid
End Class
Public Class Appointment
Inherits ReadModel
Public Property StartTime As DateTime
Public Property EndTime As DateTime
End Class
Public Class Person
Inherits ReadModel
Public Property FirstName As String
Public Property LastName As String
End Class
Public Class Repository
Private _database As IDictionary(Of Type, IDictionary(Of Guid, ReadModel))
Public Sub New()
_database = New Dictionary(Of Type, IDictionary(Of Guid, ReadModel))
End Sub
Public Sub Save(Of TReadModel As ReadModel)(readmodel As TReadModel)
If Not _database.ContainsKey(GetType(TReadModel)) Then
_database.Add(GetType(TReadModel), New Dictionary(Of Guid, ReadModel))
End If
_database(GetType(TReadModel)).Add(readmodel.Id, readmodel)
End Sub
Public Function Load(Of TReadModel As ReadModel)(id As Guid) As TReadModel
Return CType(_database(GetType(TReadModel))(id), TReadModel)
End Function
End Class
<TestClass()>
Public Class RepositoryTests
<TestMethod()>
Public Sub PersonRepositoryTest()
Dim repo As New Repository
Dim person1 = New Person() With {.Id = Guid.NewGuid, .FirstName = "Dom", .LastName = "Finn"}
Dim person2 = New Person() With {.Id = Guid.NewGuid, .FirstName = "Billy", .LastName = "Finn"}
repo.Save(Of Person)(person1)
repo.Save(Of Person)(person2)
Dim person1Loaded = repo.Load(Of Person)(person1.Id)
Assert.IsNotNull(person1)
End Sub
<TestMethod()>
Public Sub AppointmentRepositoryTest()
Dim repo As New Repository
Dim app1 = New Appointment() With {.Id = Guid.NewGuid, .StartTime = New DateTime(2015, 1, 1, 9, 0, 0), .EndTime = New DateTime(2015, 1, 1, 9, 30, 0)}
Dim app2 = New Appointment() With {.Id = Guid.NewGuid, .StartTime = New DateTime(2015, 1, 2, 9, 0, 0), .EndTime = New DateTime(2015, 1, 2, 9, 30, 0)}
repo.Save(Of Appointment)(app1)
repo.Save(Of Appointment)(app2)
Dim person1Loaded = repo.Load(Of Appointment)(app1.Id)
Assert.IsNotNull(app1)
End Sub
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment