C # creating attribute indicating current code after property call

I would like to create an attribute to add properties.

The properties that will contain this attribute will execute another method after setting a new value.

For instance:

[MethodExecute(Log)] [MethodExecute(Save)] public string Name { get { return name; } set { name = value; } } 

Here I would like to activate two methods: one will record the changes and the other will save them.

Thanks, Ronny

+4
source share
3 answers

I believe you can do this in PostSharp . You need to specify the method name as a string, unfortunately - there is no operator in C # to resolve the method name in MethodInfo , although this has been suggested several times.

You may need to move the attribute if you want the code to execute only after the installer (and not the receiver):

 public string Name { get; [MethodExecute("Log")] [MethodExecute("Save")] set; } 

(For simplicity, an automatically implemented property is used.)

+5
source

What are you really asking about if there are any interceptors in the .NET framework for Aspect-Oriented Programming (AOP). Unfortunately, the answer is no, not the default.

There are many frameworks that allow you to do this, but most of them require types designed in this way to be created by a specialized factory.

  • Many DI containers have so-called interception capabilities that allow you to do this. An example of such a DI container is Castle Windsor .
  • Microsoftโ€™s examples and practices once introduced a policy implementation application block that allows this scenario.
  • In more specialized cases, you also see this in certain substructures - for example, ASP.NET MVC has something called ActionFilter, which works just that, but only when placed in the MVC pipeline.

There are also several frameworks that allow you to do this by changing the IL after compiling it, but as I understand it, there are some pretty serious flaws.

+1
source

All Articles