.Net compiler hooking
All my data objects implement an interface IFillable
Public Interface IFillable
Sub Fill(ByVal Datareader As Data.IDataReader)
End Interface
In the objects themselves you will typically see something like
Public Class Supplier
Implements IFillable
Public Sub New()
End Sub
Public Sub New(ByVal SupplierID As Guid, ByVal CompanyID As Guid, ByVal Description As String)
Me._SupplierID = SupplierID
Me._CompanyID = CompanyID
Me._Description = Description
End Sub
Public Property SupplierID As Guid
Public Property CompanyID As Guid
Public Property Description As String
Public Sub Fill(ByVal Datareader As System.Data.IDataReader) Implements IFillable.Fill
If Not Datareader.IsClosed Then
Me._SupplierID = Datareader.GetGuid(Datareader.GetOrdinal("SupplierID"))
Me._Co开发者_JS百科mpanyID = Datareader.GetGuid(Datareader.GetOrdinal("CompanyID"))
Me._Description = Datareader.GetString(Datareader.GetOrdinal("Description"))
End If
End Sub
End Class
Now here is the tricky bit. Given that all my property names WILL ALWAYS match my database column names what I want to do is using reflection generate the fill method at compile time and infer the types and column names for the datareader.
I am assuming I will need to structure this functionality as some sort of a tool/vs plugin? What I am looking for is guidance on the best way to go about this.
PS: BTW: Obviously I could easily do this using reflection at runtime but I dont want to take the performance hit for it (Although theoretically if I could cache the values somehow (static class?) it might not be too bad).
Why don't you use a simple generator in a 'before-build' step to create the code.
We've created our own code generator that generates an in code Data Layer when triggered manually after a database definition change.
I would recommend to use some code generation framework. For VB/C#/.NET the most obvious choice should be T4: some T4 introduction
You could look at “aspect-oriented programming” systems for C#, some of them work at compile time, e.g
PostSharp reads .NET binary modules to an object model, let plugins analyze and transform it, then writes it back to MSIL.
There is a list of them here, I have never used any of them on a project but have thought of doing so for problems like yours.
A source code generation framework is also a good opion and can be a lot easer to understand what is going on.
精彩评论