web 2.0

Archive: Strongly Typed Resources ... Care of DynamicProxy2

 

Whilst discussing Globalization and Localization on the current SharePoint stuff I am working on, the issue of resource files, their location, their abstraction, and their general use came up.
One option was to use resgen.exe to create strongly typed classes for the resources, but I felt that this lost us the flexibility that dropping the .resx files into app_globalresources would provide us with.  Although accessing the compiled resources from the AppDomain is easy enough (look for an assembly called "app_GlobalResources"), we would then lose the strong typing, and have to resort to:

ResourceManager rm =new ResourceManager(... ,...);
    rm.GetString("MyNonTypedName");

So to work around this I spent a bit of time looking into DynamicProxy2 from the Castle stack. After a few interesting diversions into the world of DictionaryAdapter (thanks to Ken Egozii and Josh Robb. Sadly poorly documented, but I'm sure it will prove invaluable soon), I finally came up with the simple bit of code I was trying to achieve:

public class SpikeProxyResources
    {
        [Test]
        publicvoid Test()
        {
            ProxyGenerator pg =new ProxyGenerator();
 
            IResource proxy = pg.CreateInterfaceProxyWithoutTarget<IResource>(new MyInterceptor());
 
            string s = proxy.GetVal;
           
            Assert.AreEqual("GetVal", s);
 
            Assert.AreEqual("NewValue", proxy.NewValue);
        }
    }
 
    public interface IResource
    {
        string GetVal { get;}
 
        string NewValue { get; }
    }
 
    public class MyInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.Name.StartsWith("get_"))
            {
                //TODO: Lookup resource here....
                invocation.ReturnValue = invocation.Method.Name.Substring(4);
            }
            else
                invocation.ReturnValue =null;
        }
    }

Fundamentally, this allows us to intercept the calls to the getter on IResource, and look up the resource we are after within the compiled resources. For the moment it may only return the called Method Name, but only because I saved you the boring bit that goes off and gets back the real value.
IResource can now be instantiated by Windsor and adding more strongly typed resources is just a matter of adding a get property onto the interface.
 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

architecture | patterns and practices