C # Run the code snippet before the properties are deleted.

I have a method that I would like to always run before accessing the property. Is this possible without manually starting the method inside get {}? here is an example of what i want to work with.

private string _someString; private string _someOtherString; public string SomeString { get { return _someString; } } public string SomeOtherString { get { return _someOtherString; } } public void AlwaysRun() { // Code to always run here. } 
+4
source share
3 answers

This is not possible natively in the .NET platform.

But this can be done using a method known as AOP, Aspect-oriented programming. There is a good explanation here: http://www.sharpcrafters.com/aop.net . AOP - all about entering code before or after a method call; this is what you want to do. There are two ways to do this: at run time or at compile time. The execution path creates dynamic dynamics by overriding virtual methods, so in order for your methods to be virtual, your methods become virtual. If this is compilation time, the actual code (or IL) changes.

Good compilation of AOP framework PostSharp . To run AOP in runtime, an example structure might be Castle DynamicProxy .

+5
source

You can do this with dynamic proxies if the properties are virtual. A dynamic proxy server will override getters and setters, notify you of the call, and then run the original method. Otherwise, copy paste the call everywhere manually.

+1
source

You can use the dependency injection infrastructure such as Unity, Ninject, Castle Windsor and implement Interceptor. The task of the interceptor is to intercept the call to something, for example a method, and do something like registration with it.

fejesjoco mentioned dynamic proxies, and they are used by Castle Windsor to intercept method calls.

This is a great topic for this format, but if you're interested, go to Google ninject and follow the instructions on that. How large software systems come together to be flexible and provide future change.

0
source

Source: https://habr.com/ru/post/1333822/


All Articles