Valid alternatives to the strongly-typed Static resource class 2/2



Here follow 3 alternatives to the static strong typed class automatically generated by Visual Studio (2005, 2008, 2010) to get access to the resources (in .resx files) .


All are great examples of how to exploit the technology to improve the design of the application instead of writing fragile rigid code highly coupled with a specific technology solution.










One alternative is to create an instance class that wrap the static class, it will contain a property get for every resource expesed by the static class. Basically instance class methods are a 1:1 mapping of the static class ones. The instance class will implement also an interface that contains all the properties gets. The classes using the static class now will have the instance class injected in the constructor with the type of the interface. This enable future changes of  the way resources are stored and retrieved (i.e. move them to the db or switch to a 3rd party library for the localization).
Pros: adherence to OCP and DIP
Cons: require to write the wrapper for every static resource class. With a tool like Resharper and knowing the rights shortcuts it become a matter of few seconds anyway.



Another alternative is to replace the hand written wrapper with a Proxy automatically created by the .NET Remoting infrastructure. Given the interface with all the expected property gets the automatically created Proxy  will do the 1:1 mapping. Here the implementation of the automatic proxy: http://www.pastie.org/1616663
Pros: adherence to OCP and DIP + no need of the hand written wrapper
Cons:  still need of the hand written interface, the automatic Proxy at run-time will be a little slower of the hand-written proxy because the use of the reflection. can fail at run-time when i.e. a resource is deleted and the interface is not updated aacordingly.



Third alternative is to use T4, the VS Text Template Transformation Toolkit for code generation, to generate automatically both the interface and the static class wrapper. This is a great alternative to the unnecessarely complex and unstable  technology (changes at every new VS version) required to write your custom version of the VS resource code generator.
You can us this alternative for the interface and use the proxy for the wrapper (in order to have less code to compile and maintain) or you can automatically generate both.
Pros: adherence to OCP and DIP + no need of the hand written wrapper and interface + easily shared since it is simple code that can be included in the solution
Cons:  need to be run manually when the resources change.

Thanks to Johan that inspired to me those options and imagined and implemented the T4 one :)

Print | posted @ lunedì 28 febbraio 2011 23:11

Comments have been closed on this topic.