I am trying to understand the DynamicDictionary in NancyFX, it looks pretty cool. Does anyone know of a blog post or similar, that goes through the internals of it?
I need a propertybag to pass around objects, that I don't know the content of because they come from outside my system as JSON. But based on the contents of these objects, such as the presence of certain properties I need to do stuff.
I could just pass around dynamic objects, but that is a bit too vague I think. Don't really like that.
I would need nested dictionaries, to fully represent the object graph.
The dynamic dictionary is just a ExpandoObject with a Dictionary in it. So it can still be accessed like a dictionary.
For example, in MVC you access Form properties like so:
or
When a request comes into Nancy you can access it via the dot notation. Or via the class indexer.
This is handy when you're sending query string or form names that have values that cannot be used in dot notation.
The values are also dynamic, so it could be made up of nested objects. This allows you to do stuff like:
So if you're passing a JSON payload to the request then you can access the entire structure using dot notation.
However you will probably find most developers using Nancy only ever access Route values or QueryString values using this method.
So back to the original question:
Is there a blog post or any doco: Nope.
Why does it exist: For sugar syntax.
Can I use it for what I want: Yes absolutely!
Can you tell me how to use it: Nope, however it shouldn't be hard. Just look the model binding in Nancy to figure it out. It's not too hard.
Just an edit based on the answer by the OP.
When you access the dot notation, continued dot notation will only work on further dynamic types.
This means using
varwill cause an exception because of the wayvaranddynamicare handled by the compiler.When you do:
parametersis currentlydynamicand implementsTryGetMember, this internally looks up a dictionary of values and attempts to return the value.When you define the object as
varfor thepersonvariable. The compiler assumes that anything after that exists on the object, so it looks fornameon thepersonvariable.Since
namedoes not exist as a member ofpersonit will throw.To resolve this, the variable must be assigned as
dynamic. So the example becomes:This will work.