Code on this blog can rarely be considered remotely production-worthy. Today's example could possibly take the crown as the most filthy.
First, some context. I recently was working on a project where I wanted to represent ids as custom types instead of having int
s everywhere.
I found a package - StonglyTypedId - which is a source generator to remove most of the boilerplate
for these strongly typed ids. Andrew Lock, the package author, has a series of blog posts describing this problem he calls primitive obsession as well as how this
package was designed to solve it.
In using this StronglyTypedId library with Dapper.Contrib
and MySQL I came across an issue where the .NET method
Convert.ChangeType
is used to convert from a ulong
into the generated custom PersonId
type. Convert.ChangeType
can not be extended for custom types and hence the bug.
The solution would be to either change Dapper.Contrib to use Dappers SqlMapper
type conversion system or to use the .NET TypeConverter
(example below) or some other extensible conversion method.
var converter = TypeDescriptor.GetConverter(typeof(idp.PropertyType));
var newValue = converter.ConvertFrom(id);
idp.SetValue(entityToInsert, newValue, null);
However practical a solution like that may be, it wouldn't make for a good blog post. What if, being stubborn individuals, we really wanted to extend Convert.ChangeType
? Is that possible? Where would such a persuit take us? The implementation is pretty limited and so I say replace it - my implementation is better!