ICreatingInterceptor concept

Provided with all materials about Attaching to global event EpiServer, I would build (and I did couple times) code like this:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class MyApplicationModule : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
        DataFactory.Instance.CreatingPage += CreatingPageHandler;
    }

    private static void CreatingPageHandler(object sender, PageEventArgs e)
    {
        var articlePage = e.Page as ArticlePage;
        if (articlePage != null)
        {
            // do the job with page
        }

        // repeated similar code for other pages. 
    }
}

This approach has one big problem – you deal with page far away from where it’s defined, you do it in global module. Of course you can think that Single Responsibility Principle is fulfilled, cause you have all page handlers in one place. I understand SRP in a little different way and want to share with you Interceptor Concept that uses interface for each handler:

interface ICreatingInterceptor
{
    void OnCreating(object sender, PageEventArgs e);
}

In module it just checks for interface and invokes the interface method.

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class PageEventHandlersModule : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
        DataFactory.Instance.CreatingPage += CreatingPageHandler;
    }

    private void CreatingPageHandler(object sender, PageEventArgs e)
    {
        var creatingInterceptor = e.Page as ICreatingInterceptor;
        if (creatingInterceptor != null)
        {
            creatingInterceptor.OnCreating(sender, e);
        }
    }
}

Handler fired when creating a page is just in the page:

public class ArticlePage : StandardPage, ICreatingInterceptor
{
    // (...)

    public void OnCreating(object sender, PageEventArgs e)
    {
        var articlePage = e.Page as ArticlePage;
        if (articlePage != null)
        {
            // do the job with page
        }
    }
}

And so are more interceptors like: ISaveInterceptor, IPublishingInterceptor, etc…

This approach have the most sens when you only touch page properties. Code that touches more global thinks should be kept inside appropriate modules.

What do you think?

Credits for idea goes to Maciej Grzyb.

2 Comments on “ICreatingInterceptor concept

    • Thanks for sharing a link. There is a lot of good code flying around 🙂 My reason for using page events was exactly the same like in Alf’s case – SetDefaultValues() was fired too early.