1

I am working on code for an ASP.NET MVC application that will do the following when the application is started:

  • Load all assemblies in the application bin directory
  • Get all types from each assembly that are derived from an interface (ITask)
  • Invoke the Execute() method on each type

Here is the current idea I came up with. This method will get called in OnApplicationStarted():

    private void ExecuteTasks()
    {
        List<ITask> startupTasks = new List<ITask>();
        Assembly asm = this.ExecutingAssembly;

        // get path of executing (bin) folder 
        string codeBase = this.ExecutingAssembly.CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        string bin = Path.GetDirectoryName(path);
        string[] assemblies = Directory.GetFiles(bin, "*.dll");

        foreach (String file in assemblies)
        {
            try
            {
                if (File.Exists(file))
                {
                    // load the assembly
                    asm = Assembly.LoadFrom(file);

                    // get all types from the assembly that inherit ITask
                    var query = from t in asm.GetTypes()
                                where t.IsClass &&
t.GetInterface(typeof(ITask).FullName) != null
                                select t;

                    // add types to list of startup tasks
                    foreach (Type type in query)
                    {
                        startupTasks.Add((ITask)Activator.CreateInstance(type));
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
            }
        }

        // execute each startup task
        foreach (ITask task in startupTasks)
        {
            task.Execute();
        }
    }

My question: is there a better way to do any of these steps? The method to get the bin directory was taken from this answer: https://stackoverflow.com/a/283917/213159. It seems like a lot of work to do something simple, but I couldn't figure out an easier approach.

Also, is using System.Activator to create instances and then subsequently invoke the Execute() method on each instance the most efficient way to perform that step?

Community
  • 1
  • 1
Michael Hornfeck
  • 1,242
  • 1
  • 16
  • 33

1 Answers1

0

You may be able to clean the code up, but without any extension libraries the code doesn't get all that much shorter.

About performance, I'd not worry too much about optimizing OnApplicationStarted tasks in particular, it's hopefully not called all that often and shouldn't impact your site once it's up and running.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294