AOP – Enforce initialization with PostSharp

Oh, the Pain!

Now and again we all come across an object which requires initialization before it can be used but with nothing there to stop us from trying to use it before it’s initialized.

In most cases you will get a seemingly unrelated exception (e.g. null reference when the object tries to use some resource which it expects to be set during initialization), which aren’t very helpful at all when you try to debug/identify the problem.

If you’re lucky, the object you’re using might have been designed with this in mind and gives you a meaningful exception when you try to call a method which requires the object to be initialized first, in which case it should be a straightforward to fix your code accordingly. For the guys designing the class though, this usually means they have to litter their code with validation logic and often means duplicated validation code or unnecessary inheritance just to encapsulate the validation logic.

Fortunately, with the help of PostSharp, a simple attribute can take care of this chore for you with ease!

Define high level interface

First off, you need a nice and simple interface like this:

/// <summary>
/// Marks a component which needs to be initialized before it can be used
/// </summary>
public interface IInitializable<T>
{
    bool IsInitialized { get; }

    void Initialize(T initObject);
}

InitializationRequiredAttribute

The attribute will look something like this (in PostSharp 2):

[Serializable]
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class InitializationRequiredAttribute : MethodInterceptionAspect
{
    public override bool CompileTimeValidate(MethodBase method)
    {
        // make sure that the attribute is used in a type that implements the 
        // IInitializable interface
        if (!method.DeclaringType.GetInterfaces()
                   .Any(i => i.IsGenericType &&
                             i.GetGenericTypeDefinition() == typeof(IInitializable<>)))
        {
            throw new Exception(string.Format(
                "The [{0}] attribute can only be used in types that implement the [{1}] interface",
                GetType(), typeof(IInitializable<>)));
        }
        return base.CompileTimeValidate(method);
    }

    /// <summary>
    /// Checks the IsInitialized property before allowing the call to proceed
    /// </summary>
    public override void OnInvoke(MethodInterceptionArgs eventArgs)
    {
        var propertyInfo = eventArgs.Instance.GetType().GetProperty("IsInitialized");
        if (propertyInfo != null)
        {
            var propertyValue = propertyInfo.GetValue(eventArgs.Instance, null);
            if (propertyValue != null && propertyValue is bool && (bool) propertyValue)
            {
                // only proceed with the call if the instance has been initialized
                eventArgs.Proceed();
                return;
            }
        }
        throw new InstanceNotInitializedException(eventArgs.Method.Name);
    }
}

I have enforced a rule that this attribute can only be used in a class which implements our IInitializable interface, you can relax this rule by removing the overridden CompileTimeValidate method. However, in my experience it’s best to not leave any grey area in your code just in case you run into a situation where you had expected the attribute to do its job only to find out later that something’s gone wrong because you had accidentally/purposely removed the IInitializable interface from your class.

Usage

To use the attribute:

public class MyClass : IInitializable<string>
{
    public bool IsInitialized { get; private set; }
    public void Initialize(string initializationData)
    {
        …
        IsInitialized = true;
    }

    [InitializationRequired]
    public void DoSomething() { }
}
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy