如何在c#.NET中实现健壮的插件系统?

时间:2017-04-12 08:09:09

标签: c# .net

如果由于动态加载的外部DLL实例中的任何未捕获的异常,我如何防止主机应用程序崩溃?

现在我有类似下面的设置,请注意这不是确切的实现:

internal class ExtensionManager
{
   private static Type mExtension;
   public static GetExtension() { return mExtension; }
   ExtensionManager()
   {
     FileInfo[] fis = null;
     fis = directory.GetFiles("*.dll");
     foreach (FileInfo file in fis)
     {
       Assembly assembly = Assembly.LoadFrom(file.FullName);
       if(some condition)
       {
          mExtension = Assembly.GetTypes().FirstOrDefault(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(BaseExtension)));
          break;
       }
     }
   }
}

internal class Room
{

    public Room()
    {
      StartExtensions();
    }
    private BaseExtension CreateInstance(Type classType)
    {
        BaseExtension instance = null;
        try
        {
            instance = (BaseExtension)Activator.CreateInstance(classType, new object[] { this });
        }
        catch (Exception error)
        {
            LogException("[Room][CreateInstance()]", error);
        }
        return instance;
    }

    private void StartExtensions()
    {
        if (!mExtensionInitialised)
        {
            Type classType = ExtensionManager.GetExtension();
            if (classType == null) return;
            if (classType.BaseType != typeof(BaseExtension)) return;
            Task<BaseExtension> task = Task<BaseExtension>.Factory.StartNew(() => CreateInstance(classType), TaskCreationOptions.LongRunning);
            try
            {
                task.Wait();
            }
            catch (Exception error)
            {
               //
            }
        }
    }
}

class Program
{
  static List<Room> mRooms = new List<Room>();
  static void Main(string[] args)
  {
    for(int i = 0; i < 100; i++)
    {
      Room room = new Room();
      mRooms.Add(room);
    }
  }
}

因此,我需要在BaseExtension CreateInstance(Type classType)创建的实例中的运行时确定是否存在未捕获的异常。

P.S.NET插件框架暂时不适合我。

0 个答案:

没有答案