views:

260

answers:

3

Hello,

I would like to create an Attribute to put on properties.

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

For example:

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

Here I would like to activate two methods, one will log the change and the other will save it.

Thanks, Ronny

+4  A: 

I believe you could do this in PostSharp. You'll need to specify the method name as a string unfortunately - there's no operator in C# to resolve a method name into MethodInfo, although it's been proposed a few times.

You may need to move the attribute if you need the code to execute only after the setter (rather than the getter):

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

(This uses an automatically implemented property for simplicity.)

Jon Skeet
+, I have very good experience with PostSharp.
TcKs
Working great :)
Ronny
A: 

What you are really asking about is whether the .NET framework has any hooks for Aspect-Oriented Programming (AOP). Unfortunately, the answer is no, not by default.

There are many frameworks that allow you to do this, but most require that the types so decorated are being created by a specialized factory.

  • Many DI Containers have so-colled Interception capabilities that allow you to do that. An example of such a DI Container is Castle Windsor.
  • Microsoft patterns & practices once made the Policy Injection Application Block that enables such a scenario.
  • In more specialized cases you also see this in certain sub-frameworks - e.g. ASP.NET MVC has something called ActionFilter that work that way, but only when hosted by the MVC pipeline.

There are also a few frameworks that allow you do this by modifying the IL after it was compiled, but as I understand it there are some pretty serious disadvantages as well.

Mark Seemann
A: 

You can also use interception mechanism provided by Unity dependency injection container. Consider Implementing INotifyProperyChanged with Unity Interception as an example.

Dzmitry Huba