Do I even need to "inject" code with reflection into static classes?

I am trying to make creating proxy cache classes as simple as possible. I've done some different experiments with a lightweight API for this, but it's not that simple.

Right now, I'm looking at attributes and reflections to see if it can be "magically" resolved. For example, given this class:

public static MyCache
{
  [Cache("foobar")]
  public static string Foobar { get; set; }
}

      

and let it somehow produce the equivalent

public static MyCache
{
  [Cache("foobar")]
  public static string Foobar
  {
    get
    {
      return (string)Cacher.Get("foobar");
    }
    set
    {
      Cacher.Set("foobar", value, new CacheOptions()); //or whatever
    }
  }
}

      

Whereas both versions must appear "normal" to the caller for it to be valid:

MyCache.Foobar="meh";
Assert.IsEqual("meh", MyCache.Foobar);

      

Is there anything available for me with a thought that would make something like this work?

+3


source to share


1 answer


Is there anything available for me with a thought that would make something like this work?

No, there is nothing available to achieve this, especially if the property is not virtual. If the property is virtual, you can use frameworks like Castle.DynamicProxy to do object oriented programming. Popular mocking frameworks like Rhino Mocks and NSubstitute use it to create runtime proxies. Of course, this only works with virtual participants. In the example you showed, you have a static property that cannot be weaved.



To do this, you can use post-compilation processing tools such as PostSharp

. They work by modifying the generated IL.

+2


source







All Articles