Skip to content

Repository files navigation

Icon Devlooped.Dynamically

VersionDownloadsLicense

Instantiate record types from dynamic data with compatible structural shapes, in-memory with no reflection or serialization, via compile-time source generators.

Usage

Create records for your data types:

publicrecordPoint(intX,intY);publicrecordLine(PointStart,PointEnd);publicrecordDrawing(Line[]Lines);

This project will generate a Dynamically class with a factory method to create instances of those records from a data object with a compatible shape, such as:

vardata=new{Lines=new[]{new{Start=new{X=50,Y=0},End=new{X=0,Y=100},},new{Start=new{X=50,Y=0},End=new{X=0,Y=100},}}};Drawingdrawing=Dynamically.Create<Drawing>(data);

In adition to a dynamic object (or an ExpandoObject, for example), you can also pass in objects from other strongly typed values that come from a different assembly as long as it has the same structure. This allows fast in-memory object mapping without any serialization or extra allocations.

The factory works too for Newtonsoft.Json deserialized objects, for example:

// elsewhere, you got an in-memory Json.NET object model, perhaps with:dynamicdata=JsonConvert.DeserializeObject(json);// Subsequently, you can turn it into your strongly-typed records:Drawingdrawing=Dynamically.Create<Drawing>(data);

You can also optionally customize the mapping for specific records by providing accessible static Create or CreateMany factory methods in your records, so you can selectively customize the mapping by providing them as needed in specific cases. For example:

partialrecordDrawing{// Customize creation of a single Drawing from a dynamic valuepublicstaticDrawingCreate(dynamicvalue);// Customize creation of a list of Drawings from a dynamic valuepublicstaticList<Drawing>CreateMany(dynamicvalue);}

How It Works

This package analyzes (at compile-time) the shape of your records and creates a factory that create instances from a dynamic object. For this, it just accesses the properties of the dynamic object and passes them to the record constructor (or its properties). This means that the data must have (at least) the expected values for the conversion to succeed.

The static Dynamically.Create generic method is also generated at compile time and contains a switch statement that dispatches to the correct factory based on the generic argument specified.

In addition, if the records are partial, you also get static Create and CreateMany static methods on the record type itself, for added convenience, such as:

partialrecordDrawing{publicstaticDrawingCreate(dynamicvalue);publicstaticList<Drawing>CreateMany(dynamicvalue);}

NOTE: these will only be provided if your record doesn't already have them.

Example

For the above example with Drawing/Line/Point records, you'd get a generated Dynamically type like:

staticpartialclassDynamically{publicstaticpartialTCreate<T>(dynamicdata){returntypeof(T)switch{Typetwhent==typeof(Drawing)=>(T)Drawing.Create(data),
_ =>thrownewNotSupportedException(),};}}

If the Drawing record was partial, the Create method would look like:

partialrecordDrawing{publicstaticDrawingCreate(dynamicvalue)=>DrawingFactory.Create(value);}

With the DrawingFactory class being generated as:

staticpartialclassDrawingFactory{publicstaticDrawingCreate(dynamicvalue){if(valueisnull)thrownewArgumentNullException(nameof(value));try{returnnewDrawing(Line.CreateMany(value.Lines));}catch(RuntimeBinderExceptione){varvalueAsm=((object)value).GetType().Assembly.GetName();varthisAsm=typeof(DrawingFactory).Assembly.GetName();thrownewArgumentException($"Incompatible {nameof(Drawing)} value. Cannot convert value from '{valueAsm.Name}, Version={valueAsm.Version}' to '{thisAsm.Name}, Version={thisAsm.Version}'.",nameof(value),e);}}publicstaticList<Drawing>CreateMany(dynamicvalue){varresult=newList<Drawing>();foreach(variteminvalue){result.Add(Create(item));}returnresult;}}

The Line factory method would look very similar, instantiating a many points, with perhaps Point being the most interesting:

staticpartialclassPointFactory{publicstaticPointCreate(dynamicvalue){if(valueisnull)thrownewArgumentNullException(nameof(value));try{returnnewPoint((global::System.Int32)value.X,(global::System.Int32)value.Y);}catch(RuntimeBinderExceptione){varvalueAsm=((object)value).GetType().Assembly.GetName();varthisAsm=typeof(PointFactory).Assembly.GetName();thrownewArgumentException($"Incompatible {nameof(Point)} value. Cannot convert value from '{valueAsm.Name}, Version={valueAsm.Version}' to '{thisAsm.Name}, Version={thisAsm.Version}'.",nameof(value),e);}}publicstaticList<Point>CreateMany(dynamicvalue){varresult=newList<Point>();foreach(variteminvalue){result.Add(Create(item));}returnresult;}}

As you can see, the factory methods are very simple and straightforward, and have great run-time performance characteristics since there is absolutely no reflection, and the built-in C# dynamic infrastructure takes care of doing the heavy lifting. The generated code is basically what you'd write manually to do the casting of the entire object hierarchy.

Limitations

This package is not meant to be a full-fledged object mapper. For that, you can use AutoMapper, for example, which is much more flexible and has excelent performance characteristics. This package does provide very fast in-memory object mapping that is far faster and cheaper than going through any sort of serialization.

As mentioned, the provided factories do not provide backwards-compatibility: if you add a property or constructor argument to the record, the factory will fail for payloads without it.

Dogfooding

CI VersionBuild

We also produce CI packages from branches and pull requests so you can dogfood builds as quickly as they are produced.

The CI feed is https://pkg.kzu.app/index.json.

The versioning scheme for packages is:

  • PR builds: 42.42.42-pr[NUMBER]
  • Branch builds: 42.42.42-[BRANCH].[COMMITS]

Sponsors

Clarius OrgMFB Technologies, Inc.SandRockDRIVE.NET, Inc.Keith PickfordThomas BolonKori FrancisReuben SwartzJacob FosheeEric JohnsonJonathan Ken BonnySimon Croppagileworks-euZheyu ShenVezelChilliCream4OTCdomischellAdrian AlonsotorutekRyan McCafferySeika LogicielAndrew Granteska-gmbhGeodata AS

Sponsor this project

Learn more about GitHub Sponsors

About

Instantiate record types from dynamic data with compatible structural shapes, in-memory with no reflection or serialization, via compile-time source generators.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

10 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages