Alaor
Alaor

Reputation: 2191

Get information about the decorated member by an attribute in C#

I need to know if there's any way (or another distinct approach) to an attribute knows something about what is being decorated for him. For example:

class Cat
{
    public Cat() { }

    [MyAttribute]
    public House House { get; set; }
}

Inside MyAttribute I must do some preprocessing with the house object...

class MyAttribute : Attribute
{
    public MyAttribute() 
    {
        var ob = // Discover the decorated property, do some changes and set it again
    }
}

I don't know if it's the better way, neither if it actually can be done,

Upvotes: 3

Views: 1862

Answers (2)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422132

This is not how attributes work. They are just compile time metadata added to something. They don't accomplish anything by themselves. At runtime, code can use that metadata to do things.

UPDATE: Basically, as I understand, you are trying to accomplish two things. The first is to tell the repository not to load some properties. Attributes can be used for this purpose but the repository code should use reflection on the entity type and see what it shouldn't load in the first place. The second thing is that you want to have the property loaded as it's called for the first time. You need to check if it's already loaded or not on each call and load it the first time it's called. This can be achieved by manually inserting such a code or using something like PostSharp which post-processes code and can inject method calls automatically by looking at the attributes. Probably, this is what you asked for in the first place.

Upvotes: 3

JP Alioto
JP Alioto

Reputation: 45127

What you want is the Policy Injection application block in EntLib.

Developers can use the Policy Injection Application Block to specify crosscutting behavior of objects in terms of a set of policies. A policy is the combination of a series of handlers that execute when client code calls methods of the class and—with the exception of attribute-based policies—a series of matching rules that select the classes and class members (methods and properties) to which the application block attaches the handlers.

Upvotes: 1

Related Questions