C# DLL config file

后端 未结 17 2377
梦毁少年i
梦毁少年i 2020-11-22 05:05

Im trying to add an app.config file to my DLL, but all attempts have failed.

According to MusicGenesis in \'Putting configuration information in a DLL\' this should

相关标签:
17条回答
  • 2020-11-22 05:11

    Seems like this config files are really confusing to clarify as their behaviour changes from the dev environment to deployment. Apparently a DLL can have its own config file, but once you copy and paste the dll (together with their config file) elsewhere, the whole thing stopped working. The only solution is to manually merge the app.config files into a single file, which will only be used by the exec. For e.g. myapp.exe will have a myapp.exe.config file that contains all settings for all dlls used by myapp.exe. I'm using VS 2008.

    0 讨论(0)
  • 2020-11-22 05:12

    For a dll, it should not depend on configuration as configuration is owned by application and not by dll.

    This is explained at here

    0 讨论(0)
  • 2020-11-22 05:14

    you can use this code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace GClass1
    {
    [Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _GesGasConnect
    {
        [DispId(1)]
        int SetClass1Ver(string version);
    
    
    }
    
    [Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("InterfacesSMS.Setting")]
    public class Class1 : _Class1
    {
        public Class1() { }
    
    
        public int SetClass1(string version)
        {
            return (DateTime.Today.Day);
        }
    }
    }
    
    0 讨论(0)
  • 2020-11-22 05:18

    It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

    There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

    Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

    The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

    Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

    Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

    The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

    If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

    0 讨论(0)
  • 2020-11-22 05:19

    ConfigurationManager.AppSettings returns the settings defined for the application, not for the specific DLL, you can access them but it's the application settings that will be returned.

    If you're using you dll from another application then the ConnectionString shall be in the app.settings of the application.

    0 讨论(0)
  • 2020-11-22 05:25

    I had the same problem and searched the web for several hours but I couldn't find any solution so I made my own. I wondered why the .net configuration system is so inflexible.

    Background: I want to have my DAL.dll to have its own config file for database and DAL settings. I also need the app.config for Enterprise Library and its own configurations. So I need both the app.config and dll.config.

    What I did not wanted to do is pass-through every property/setting from the app to my DAL layer!

    to bend the "AppDomain.CurrentDomain.SetupInformation.ConfigurationFile" is not possible because I need it for the normal app.config behavior.

    My requirements/point of views were:

    • NO manual copy of anything from ClassLibrary1.dll.config to WindowsFormsApplication1.exe.config because this is unreproducible for other developers.
    • retain the usage of strong typing "Properties.Settings.Default.NameOfValue" (Settings behavior) because I think this is a major feature and I didn't want to lose it
    • I found out the lack of ApplicationSettingsBase to inject your own/custom config file or management (all necessary fields are private in these classes)
    • the usage of "configSource" file redirection is not possible because we would have to copy/rewrite the ClassLibrary1.dll.config and provide several XML files for several sections (I also didn't like this)
    • I didn't like to write my own SettingsProvider for this simple task as MSDN suggests because I thought that simply would be too much
    • I only need sections applicationSettings and connectionStrings from the config file

    I came up with modifying the Settings.cs file and implemented a method that opens the ClassLibrary1.dll.config and reads the section information in a private field. After that, I've overriden "this[string propertyName]" so the generated Settings.Desginer.cs calls into my new Property instead of the base class. There the setting is read out of the List.

    Finally there is the following code:

    internal sealed partial class Settings
    {
        private List<ConfigurationElement> list;
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Settings"/> class.
        /// </summary>
        public Settings()
        {
            this.OpenAndStoreConfiguration();
        }
    
        /// <summary>
        /// Opens the dll.config file and reads its sections into a private List of ConfigurationElement.
        /// </summary>
        private void OpenAndStoreConfiguration()
        {
            string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            Uri p = new Uri(codebase);
            string localPath = p.LocalPath;
            string executingFilename = System.IO.Path.GetFileNameWithoutExtension(localPath);
            string sectionGroupName = "applicationSettings";
            string sectionName = executingFilename + ".Properties.Settings";
            string configName = localPath + ".config";
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configName;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    
            // read section of properties
            var sectionGroup = config.GetSectionGroup(sectionGroupName);
            var settingsSection = (ClientSettingsSection)sectionGroup.Sections[sectionName];
            list = settingsSection.Settings.OfType<ConfigurationElement>().ToList();
    
            // read section of Connectionstrings
            var sections = config.Sections.OfType<ConfigurationSection>();
            var connSection = (from section in sections
                               where section.GetType() == typeof(ConnectionStringsSection)
                               select section).FirstOrDefault() as ConnectionStringsSection;
            if (connSection != null)
            {
                list.AddRange(connSection.ConnectionStrings.Cast<ConfigurationElement>());
            }
        }
    
        /// <summary>
        /// Gets or sets the <see cref="System.Object"/> with the specified property name.
        /// </summary>
        /// <value></value>
        public override object this[string propertyName]
        {
            get
            {
                var result = (from item in list
                             where Convert.ToString(item.ElementInformation.Properties["name"].Value) == propertyName
                             select item).FirstOrDefault();
                if (result != null)
                {
                    if (result.ElementInformation.Type == typeof(ConnectionStringSettings))
                    {
                        return result.ElementInformation.Properties["connectionString"].Value;
                    }
                    else if (result.ElementInformation.Type == typeof(SettingElement))
                    {
                        return result.ElementInformation.Properties["value"].Value;
                    }
                }
                return null;
            }
            // ignore
            set
            {
                base[propertyName] = value;
            }
        }
    

    You just will have to copy your ClassLibrary1.dll.config from the ClassLibrary1 output directory to your application's output directory. Perhaps someone will find it useful.

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