开发者

C# Run a piece of code before properties are hit

I have a method that I would like to always run before the get accessor of a property. Is this possible without manually running the method inside the get{}? here's an example of what I want to work.

    private string _someString;
    private string _someOtherString;

    public string SomeString
    {
        get { return _someString; }
    }

    public string SomeOtherString
    {
        get { return _someOtherString; }
    }

    public v开发者_开发百科oid AlwaysRun()
    {
        // Code to always run here.
    }


This is not possible natively in the .NET framework.

But it can be done using a technique known as AOP, Aspect-oriented programming. There is a good explanation here: http://www.sharpcrafters.com/aop.net. AOP is all about injecting code before or after a method call; which is what you want to do. There are 2 ways to do this: At runtime or at compile time. The runtime way generates the implementation dynamically by overriding virtual methods, so it requires your methods to be virtual. If doing it compile time, the actual code (or IL) is modified.

A nice compile time AOP framework is PostSharp. For doing runtime AOP, an example of a framework could be Castle DynamicProxy.


You can do this with dynamic proxies if the properties are virtual. A dynamic proxy would override the getters and setters, notify you when they're called, and then run the original method. Otherwise, copy-paste the call everywhere manually.


You can use a dependency injection framework such as Unity, Ninject, Castle Windsor and implement an Interceptor. The job of the interceptor is to intercept a call to something such as a method and do something with it such as logging.

fejesjoco mentioned dynamic proxies and those are used by Castle Windsor to do interception of method calls as well.

That's a big topic for this format but if you are interested then google ninject interception and follow a tutorial on it. That's the way large software systems are put together to be flexible and provide for future change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜