views:

51

answers:

2

Hi, I would like to pass certain data from an instance of an object to its attribute, and I have troubles inderstanding how to implement it. Here's a sample:

[AuthenticateAttribute]
public class MyController: Controller
{
    UserInfo info;
}

The idea is that AuthenticateAttribute instance would populate the UserInfo instance.

I want to pass reference to info to an instance of AuthenticateAttribute and thereby eliminate strong coupling between the attribute and the particular MyController class.

Is this possible?

+1  A: 

The attribute itself shouldn't have the UserInfo field IMO. Bear in mind that there will be one instance of the attribute for the type it's applied to - not one per instance of that type.

If you could give a fuller example (showing the code it's applied to) we may be able to help more...

Jon Skeet
That's very new news to me, thanks.Does this mean an attribute should necessarily be aware of the internals of the type it's being applied to if there's a need to alter certain fields of the type?
Andy
@Andy: I think it's quite unusual for it to alter fields of the type itself. Usually the attribute provides metadata for other code to use - it's more passive than active.
Jon Skeet
A: 

The ViewData collection of the controller is accessible from the attribute and you can add your UserInfo object to it and then access it in the controller's acions. You can also use the a typed model containing UserInfo. This scenario is described here http://stackoverflow.com/questions/1938835/get-permission-from-authorize-attribute

Changing type fields in attribute that is applied to it is not common and you have to be very cautious.

Branislav Abadjimarinov
thanks, this is not what I was looking for. My concern was primarily about the interaction between a Controller instance and its attrubites.
Andy