Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does dynamically casting Microsoft.Azure.Documents result in deserialization?

My team was given a sample file that demonstrates how to interface with CosmosDB in C# and convert resulting Microsoft.Azure.Document instances into POCOs. The documents are converted like this: (Ellipses indicate left out logic for concision)

public Task<T> GetItemAsync<T> (...)
{

    Document document = await client.ReadDocumentAsync(...);
    return (T)(dynamic)document;

}

It appears to me that (dynamic)document somehow serializes the document which would otherwise need to be done by specifying each JSON field individually. Seeing as how dynamic cast operations cannot be overloaded, I am at a loss as to what causes this deserialization to occur.

What am I overlooking that is preventing me from understanding this operation?

like image 497
JSON Brody Avatar asked Jan 26 '23 19:01

JSON Brody


1 Answers

There is a misconception here about what is actually happening behind the scenes.

Some background first

ReadDocumentAsync returns a DocumentResponse<Document> which wraps a Document containing the read resource record.

DocumentResponse<Document> in turn has an implicit operator that that allow it to be converted/cast to Document

hence

Document item = await client.ReadDocumentAsync<T>(...);
//replaced var for to Document for demonstrative purposes.

Document is derived from IDynamicMetaObjectProvider

public class Document : Microsoft.Azure.Documents.Resource, System.Dynamic.IDynamicMetaObjectProvider

// Inheritance: Object --> JsonSerializable --> Resource --> Document
// Implements: IDynamicMetaObjectProvider

Represents a dynamic object, that can have its operations bound at runtime.

epmhasis mine

It is because of the IDynamicMetaObjectProvider that it is first cast to dynamic and then to the desired type.

Behind the scenes the dynamic resource object will try to bind the contained members of the parsed document to that of the target strongly typed object.

Saves you having to try and write an explicit conversion yourself for your desired types.

You could have also used the generic overload as suggested in another answer.

like image 180
Nkosi Avatar answered Jan 29 '23 23:01

Nkosi