Geeks With Blogs
Marcin Celej blog

Many times in my development live I had to plug-in some code into an existing application that should be xeceuted during startup / cleanup / ... . If you own the application you can always hardcode another line of code that invokes your static initialization class. But:

  • What to do if a circular dependency occurs?
  • Is the hardcoding clean?

In such case there is a pattern (or snippet) that allows you to plug-in some dynamic invocation of code. Below is an example how to declare Init method in a MyStartup class. The class implements IInit interface and is pointed by [Init] attribute. Without an further explanation the sample tells us to execute the startup during application initialization.

[assembly: Init(typeof(MyNamespace.MyStartup))]

namespace MyNamespace
{
public class MyStartup : IInit
{
public void Init()
{
// Do something - e.g. format all drives } } }

Below is code required for the above initailization to compile. Do NOT read it - you will get bored.

public interface IInit
{
void Init();
}

[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class InitAttribute : Attribute
{
private Type _startupType;
public Type StartupType
{
get { return _startupType; }
}

public InitAttribute(Type startupType)
{
if (startupType == null)
throw new ArgumentNullException("type");

if (typeof(IInit).IsAssignableFrom(startupType) == false)
throw new ArgumentException(
String.Format("Type {0} does not implement IInit interface.", startupType));

this._startupType = startupType;
}

internal static void InvokeInit(IEnumerable<Assembly> assemblies)
{
foreach (Assembly assembly in assemblies)
{
foreach (InitAttribute attr in assembly.GetCustomAttributes(typeof(InitAttribute), true))
{
IInit startup = (IInit)Activator.CreateInstance(attr.StartupType);
startup.Init();
}
}
}
}

When you have such a code all you need is to invoke InitAttribute.InvokeInit(...) passing assemblies you want to traverse during application initialization.

Off course one can add some additional logic to the initailization - e.g. dependency (so you could tell that your init should be run after some other init) or other methods invoked during other application stages - e.g. CleanUp().

I believe this approach is intuitive and clean. Maybe it is known for all of you byt maybe not. Try it out.

Posted on Monday, October 8, 2007 7:05 AM | Back to top


Comments on this post: Plugging-in application initialization code

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Marcin Celej | Powered by: GeeksWithBlogs.net