.Net app.config in library project

后端 未结 4 553
轻奢々
轻奢々 2020-12-03 23:56

I have a console application project and library project (dll) in one solution. The library project has app.config file where I store a connection string to database. The c

4条回答
  •  半阙折子戏
    2020-12-04 00:39

    By default, each process will use it's own configuration file. If you want the console application to have a configuration file you will need to add that to your project. After adding the App.config to your project whenever your project is built the App.config will be copied to the output folder as .exe.config where is your application name (e.g. ConsoleApplication1.exe.config). (Web.config is more complicated.)

    Typically, configuration is then added to this application configuration file.

    So the easiest way to configure your library assembly is to add its specific configuration to the hosting application's configuration file.

    Now that can be a bit ugly. One way to make it less ugly is to have the application configuration file simply reference your config file using the ConfigSource attribute. That way you can deploy your assembly along with your config file and simply have the hosting application add a few lines to their config file to reference your config. First they have to add a reference to the configSections:

      
        

    Next they need to add a reference to your config file:

    
    

    Now, maybe you don't want the users of your assembly to even know there is a configuration file. If that is the case, you could create your own standalone configuration file and open it up using ConfigurationManager.OpenMappedExeConfiguration. Here is another example on how to use OpenMappedExeConfiguration.

提交回复
热议问题