Reputation: 3064
Is there a way to achieve this without injection? Topic is a UserControl. I am trying to check for Title and set it in Attribute.
public partial class Topic: TopicBase
{
[Topic(Title = "My Topic")]
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
}
When I look for the Attribute I get null in TopicBase.cs
protected override void OnInit(EventArgs e)
{
var topicAttr = Attribute.GetCustomAttribute(this.GetType(), typeof(TopicAttribute)); //topicAttr is null here.
if (topicAttr != null)
{
SetTopic(((TopicAttribute)topicAttr).Title);
}
}
Upvotes: 1
Views: 131
Reputation: 426
As nvoigt said, you're trying to find the attributes of your class but you should use a MemberInfo of your method.
Something like that:
MethodInfo methodInfo = typeof(Topic).GetMethod("OnInit", BindingFlags.NonPublic | BindingFlags.Instance);
var attribute = methodInfo.GetCustomAttribute(typeof(TopicAttribute));
Upvotes: 2
Reputation: 77364
You are checking for the attribute on your type. Your attribute sits on the method. Either change your query or put the attribute on the type as expected by your query:
[Topic(Title = "My Topic")]
public partial class Topic : TopicBase
{
}
Upvotes: 2