Getting the hold on dynamic

It has to be clear that I am none of an early adopter when it comes to new technologies. Not so long ago I described my joy of discovering a use of optional and named arguments. Now is the time of dynamic.


Ok, you got me, I had used dynamic before, for example, when using Nancy to access route data or when parsing JSON data returned by EasyHttp. But that was using someone else dynamic APIs not designing mine.

My usage also bridges the gap between a dynamic reality and the static world of C#. That reality corresponds to localizable messages in web pages.
Localization can be resolved in many ways. When using resource files embedded in assemblies, Visual Studio creates the plumbing code to be able to access resource messages in .rex files through a static type. Since we chose to persist our resources inside a database we get no help from Visual Studio and were not in the mood to create a code generator to be able to write something like resources.name_of_resource when resources are needed outside a web page (where <%$Resources:resourceGroup, name_of_resource %> syntax is used).

Of course, we can do the good old resourceProvidedFactory.GetResource(“resourceGroup”, “resource”), but, let’s face it, now we can do better than that with very little effort:

Create a class that inherits from DynamicObject:

public class DynamicMessage : DynamicObject
    private static string getResource(string resource)
        return ResourceLoaderFactory.Current.GetResource("resourceGroup", resource);

    public override bool TryGetMember(GetMemberBinder binder, out object result)
        result = getResource(binder.Name);
        return true;

That piece of code defers all member invocations (properties, fields) to the TryGetMembers() method. Which will delegate on the existing resource infrastructure to get a localized message. And we can use it simply by:

dynamic resources = new DynamicMessage();
string resource = resources.name_of_resource;

Done. A class less than 10 lines of code and we can go home. Thanks, dynamic, I do not always like you, but I appreciate when you make things easy for syntactic cuteness.

Categories: Udvikling

Tagged as: ,

Skriv et svar