将一个a项目以dll的方式插入到主项目,主项目以反射的方式访问该项目

主项目需要传入用户名、密码、数据库连接参数等等数据传入到a项目,来实现对a项目的访问,根据实际情况来写接口,以下是一个接口,放在项目中,该接口也会生成一个dll

下面是接口代码:

#region 程序集 PlugInterface.dll, v1.0.0.0
// E:\LSIP\LSIP\PlugInterface\bin\Release\PlugInterface.dll
#endregion

using System;

namespace PlugInterface
{
    public interface PlugInterfaceBase
    {
        string GetPlugID();
        void SetConfigure(string UserID);
        void SetDEVorENV(string para);
        void SetLIPConnStr(string LIPConnStr);
    }
}

a项目引入该接口dll

并实现接口中的方法:

  public partial class frmMain : Form, PlugInterface.PlugInterfaceBase
    {
 

public void SetConfigure(string UserID)
        {
            Util.Configure.UserID = UserID;
        }

        public void SetLIPConnStr(string LIPConnStr)
        {
            Util.Configure.LIPConnStr = LIPConnStr;
        }

        public string GetPlugID()
        {
            return "20200108";
        }


        public void SetDEVorENV(string para)
        {
            if (para == "0")
            {
                Util.DBOperation.connstr = SLC.SCP.Util.DBOperation.SelectLIP("select ConnPara from SysDBPara where ID=5").Rows[0][0].ToString();
                //Util.Configure.MESConnStr = @"Data Source=172.16.1.3;Initial Catalog=X91BASE;uid=ReportUser;pwd=ReportPassword";
                //Util.Configure.sapid = "800";
                //Util.Configure.SysEnvir = "正式环境";
            }
            else
            {
                Util.DBOperation.connstr = SLC.SCP.Util.DBOperation.SelectLIP("select ConnPara from SysDBPara where ID=5").Rows[0][0].ToString();
                //Util.Configure.MESConnStr = @"Data Source=172.16.1.3;Initial Catalog=SAPToMes170922_20180823;uid=ReportUser;pwd=ReportPassword";
                //Util.Configure.sapid = "408";
                //Util.Configure.SysEnvir = "测试系统";
            }
        }

主项目的编译路径需要引入a项目的dll(不是引用,只是拷贝到编译路径),并用反射进行访问:

以下是部分关键代码:

else if (e.Node.Name == "80000004")
                    {
                        object obj = Assembly.LoadFile(Application.StartupPath + "\\LaboratoryProcessSZ.dll").CreateInstance("SLC.SCP.UI.frmMain");//反射
                        PlugInterface.PlugInterfaceBase inter = (PlugInterface.PlugInterfaceBase)obj;
                        inter.SetConfigure(Util.Configure.UserID);
                        inter.SetLIPConnStr(Util.Configure.ConnStr);
                        inter.SetDEVorENV(Util.Configure.SysEnvir == "正式环境" ? "0" : "1");//Util.Configure.SysEnvir = "正式环境"
                        Form fr = (Form)obj;
                        fr.ShowDialog();
                    }

a项目的编译方式如下:都选择Any CPU

否则选择其他编译方式,会出现以下错误:

发布了30 篇原创文章 · 获赞 2 · 访问量 6599

猜你喜欢

转载自blog.csdn.net/tangliuqing/article/details/105225644