Friday, March 17, 2023

A short list of C# coding issues.

Injecting services into entities

It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts with a little entity class to do X. Then, oh, I'd like to be able to do some logging, so take an ILogger<X> as constructor problem..

Woops; now I need a wrapper or some outer factory style XFactory to provide the logger service... It's not too bad I suppose, just a bit cumbersome. 

Entities with async construction

Ok, yes, I know; a constructor should be a fairly dumb operation. The constructor's goal is (mor or less) to validate and preserve input parameters. 

But some times.. particularly if your trying to break out of a Service + DTO view of the world, an entity may need to call an async service method during creation.

Years ago this problem presented with C++ on windows, generally solved with a 2-phase construction.

2-phase is a valid pattern for richer entities, but id does introduce:
  • Created entity is NOT immediately usable.
  • Entity code now generally needs safety code to throw if not fully initialised 

Typed strings with serialization

Not quite sure what to call this. 

Often data is expressed as a string, but with some constraints. For instance a PathString will always start with a '/'. This can be a very useful constraint, particularly for string concatenation etc.

 I also find myself writing constrained string classes for jobs like ensuring a valid Kubernetes entity name.

But as I've done a few times now, I then need patterns to serialize / deserialize these typed-strings, and to cleanly use them with other code.


I'm hoping to soon publish a package for these issues; currently trialling a pattern, we'll see.

No comments:

Post a Comment

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...