I have written an aspect implementing IInstanceScopedAspect and inheriting from LocationInterceptionAspect.
When initialized, it reads some properties from the target object. The problem is that IInstanceScopedAspect.RuntimeInitializeInstance() is called before the target object's constructors have run. So the target object is not fully initialized and reading its properties leads to all kinds of nasty behavior.
How can I be notified when the target object has been fully initialized (that is, all its constructors have run)? My attribute is not applied directly to the target class but to one or more of its properties.
The RuntimeInitializeInstance is meant to initialize your aspect when PostSharp creates a new instance. It's going to always be called before your class is initialized. What exactly is your aspect needing to do at the point of instantiation of the object when your aspect is a locationinterceptionaspect?
I suggest creating a complex aspect that includes an OnExit advice that targets constructors and this advice will be run after any constructor runs. In the OnExit advice, do the work you need there. your object will be initialized by then.
So your complex aspect would include your locationinterception advices and an additional OnMethodExitAdvice.
Check out these articles on how to do this:
http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-12-e28093-Aspect-Providers-e28093-Part-1.aspx
http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-13-e28093-Aspect-Providers-e28093-Part-2.aspx
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ExampleClass ec = new ExampleClass();
ec.ID = 10;
Console.ReadKey();
}
}
[ComplexAspect]
class ExampleClass
{
public int ID { get; set; }
public string Name { get; set; }
public ExampleClass()
{
//Setup
Name = "John Smith";
}
}
[Serializable]
public class ComplexAspect : InstanceLevelAspect
{
[OnMethodExitAdvice, MulticastPointcut(MemberName=".ctor")]
public void OnExit(MethodExecutionArgs args)
{
//Object should be initialized, do work.
string value = ((ExampleClass)args.Instance).Name;
Console.WriteLine("Name is " + value);
}
[OnLocationGetValueAdvice, MulticastPointcut(Targets=MulticastTargets.Property )]
public void OnGetValue(LocationInterceptionArgs args)
{
Console.WriteLine("Get value for " + args.LocationName);
args.ProceedGetValue();
}
[OnLocationSetValueAdvice, MulticastPointcut(Targets = MulticastTargets.Property)]
public void OnSetValue(LocationInterceptionArgs args)
{
Console.WriteLine("Set value for " + args.LocationName);
args.ProceedSetValue();
}
public override void RuntimeInitializeInstance()
{
base.RuntimeInitializeInstance();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With