C# reflects a class in a Dll that implements an interface

Scenes:


In the dll , the path of the relevant implementation class dll file is configurable to realize the development of a certain driver interface , so the dll can be loaded by reflection decoupling, and the driver that implements the interface can be instantiated

Implementation steps

path:

C:\\hh\\Rh.Iot.RunConsole\\bin\\Debug\\net6.0\\DriverDll\\Rh.Iot.Driver.某个driver.dll

Requirement: The name of the Dll file is consistent with the name of the class that implements the interface,
so that when the reflection is loaded, an object like
Rh.Iot.Driver.a driver.a driver is created.

Code implementation, only the path is needed to reflect a driver, and the naming of its own project files is processed through regularization.
IDriver is an internal interface

//加载dll文件
                Assembly asm = Assembly.LoadFile(DriverPath);

                //获取类
                //Type type = asm.GetType("RH.Iot.Business.EapBaseInfoHandler.GloryMes.GloryMesReciveCheckUserInfoFromMesHandler");
                string rules = @"Rh.Iot.Driver.\S{0,100}.dll";
                var m = Regex.Matches(DriverPath, rules);
                string result = string.Empty;
                if (m != null)
                {
    
    
                    string[] strs = m[0].Value.Split('.');
                    result = m[0].Value.Replace("dll", strs[3]);
                    //Console.WriteLine(result);
                }
                else
                {
    
    
                    return false;
                }
                Type type = asm.GetType(result);

                //创建该类型的实例
                IDriver obj = (IDriver)Activator.CreateInstance(type);

                //获取该类的方法
                //MethodInfo mf = type.GetMethod("InfoHandler");
                obj.Start(DriverParas);

Only provide ideas, not complete code!
I am Gouzi, I hope you are happy!

Guess you like

Origin blog.csdn.net/weixin_38083655/article/details/125807074