【发布时间】:2012-01-12 04:17:16
【问题描述】:
我正在编写 ASP.NET MVC 应用程序的代码,该应用程序启动时将执行以下操作:
- 加载应用程序 bin 目录中的所有程序集
- 从每个程序集中获取从接口派生的所有类型 (
ITask) - 对每种类型调用
Execute()方法
这是我提出的当前想法。这个方法会在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();
}
}
我的问题:有没有更好的方法来执行这些步骤? 获取 bin 目录的方法取自这个答案:https://stackoverflow.com/a/283917/213159。做一些简单的事情似乎需要做很多工作,但我想不出更简单的方法。
另外,使用System.Activator 创建实例然后在每个实例上调用Execute() 方法是执行该步骤的最有效方法吗?
【问题讨论】:
-
您如何管理任务的执行顺序?
-
由于顺序无关紧要,因此没有任何实现。每个任务执行的内容应该独立于所有其他任务。
标签: c# asp.net-mvc reflection .net-4.0