multiple hint paths in csproj file from an text file variable

前端 未结 2 1254
灰色年华
灰色年华 2021-01-14 22:00

Context : In our application there two separate dlls which are repositories of variables configured for different types of hardware .These dlls has same na

2条回答
  •  鱼传尺愫
    2021-01-14 22:08

    You need to load the correct DLL during the startup of your application, before .Net loads it for you. NET will load the default DLL as soon as an instance of that class is created. So make sure to load the proper DLL first before you access the properties. Make sure you do not access these properties in the initial class anywhere as .Net will load it then.

    Something like this:

    class Program
    {
        static void Main(string[] args)
        {
            //var configValue = XDocument.Parse("type1").Document.Descendants("hardware").First().Value;
            var configValue = XDocument.Load("MyXmlConfig.xml").Document.Descendants("hardware").First().Value;
            if (configValue == "type1")
            {
                System.Reflection.Assembly.LoadFile(@"C:\TEMP\MyAssembly_Type1.dll");
            }
            else if (configValue == "type2")
            {
                System.Reflection.Assembly.LoadFile(@"C:\TEMP\MyAssembly_Type2.dll");
            }
    
            MyRepositoryClass.Initialize();
        }
    }
    
    static class MyRepositoryClass
    {
        public static void Initialize()
        {
            var variable1 = MyAssembly.MyRepository.Variable1;
            var variable2 = MyAssembly.MyRepository.Variable2;
            var variable3 = MyAssembly.MyRepository.Variable3;
        }
    }
    

    Alternative load the DLL on demand (when .Net asks for it):

    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    
            MyRepositoryClass.Initialize();
        }
    
        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (args.Name.Contains("MyAssembly")) //Put in the name of your assembly
            {
                //var configValue = XDocument.Parse("type1").Document.Descendants("hardware").First().Value;
                var configValue = XDocument.Load("MyXmlConfig.xml").Document.Descendants("hardware").First().Value;
                if (configValue == "type1")
                {
                    return System.Reflection.Assembly.LoadFile(@"C:\TEMP\MyAssembly_Type1.dll");
                }
                else if (configValue == "type2")
                {
                    return System.Reflection.Assembly.LoadFile(@"C:\TEMP\MyAssembly_Type2.dll");
                }
            }
            return null;
        }
    }
    

提交回复
热议问题