VB.NET dynamic plugin components

前端 未结 1 430
鱼传尺愫
鱼传尺愫 2020-12-21 11:06

I am not a VB developer but I am heading up a large project in which VB is partially used. One of the requirements is to implement a plugin architecture to support dynamical

相关标签:
1条回答
  • 2020-12-21 11:40

    This is not problem at all, take a look at my sample code. Here is abstract class that exists in separate dll:

    public abstract class ServerTask
    {
        public int TaskId { get; set;}
    
        /// <summary>
        /// Gets description for ServerTask
        /// </summary>
        public abstract string Description { get; }
    
    
    }
    

    This is code from plugin implementation:

    public class SampleTask : GP.Solutions.WF.Entities.Tasks.ServerTask
    {
    
        public override string Description
        {
            get 
            {
                return "Sample plugin";
            }
        }
    
    }
    

    And finally code from core application that loads plugin:

        /// <summary>
        /// Loads Plugin from file
        /// </summary>
        /// <param name="fileName">Full path to file</param>
        /// <param name="lockFile">Lock loaded file or not</param>
        /// <returns></returns>
        static Entities.Tasks.ServerTask LoadServerTask(string fileName, bool lockFile, int taskId)
        {
            Assembly assembly = null;
            Entities.Tasks.ServerTask serverTask = null;
            if (lockFile)
            {
                assembly = System.Reflection.Assembly.LoadFile(fileName);
            }
            else
            {
                byte[] data = Services.Common.ReadBinaryFile(fileName);
                assembly = System.Reflection.Assembly.Load(data);
            }
            Type[] types = assembly.GetTypes();
            foreach (Type t in types)
            {
                if (t.IsSubclassOf(typeof(Entities.Tasks.ServerTask)))
                {
                    serverTask = (Entities.Tasks.ServerTask)Activator.CreateInstance(t);
                    serverTask.TaskId = taskId;
                    break;
                }
            }
            if (serverTask == null)
            {
                throw new Exception("Unable to initialize to ServerTask type from library '" + fileName + "'!");
            }
            return serverTask;
        }
    

    If you are not familiar with c# just use c# to vb.net online converter.

    Happy coding and best regards! Gregor Primar

    0 讨论(0)
提交回复
热议问题