当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to Read Application.Setting from referenced Class Library

问题描述:

Scenario:

I have 2 Projects, MainApplication (which compiles to an exe) and ClassLibrary1.

Now MainApplication references or loads ClassLibrary1, but ClassLibrary1 has no idea about MainApplication.

But I want to use Settings (Dot.Net 2.0's Properties.Settings NOT appSettings) that are defined in MainApplication.

How do you achieve this?

I have seem PLENTY examples that use

System.Configuration.ConfigurationSettings.AppSettings.Get("SettingName");

This is NOT relevant to my situation as appSettings is old school and I am using the newer Properties.Settings mechanisms.

Your help is appreciated :)

网友答案:

I have done some investigating in code. I can get the setting like this but it is really dirty:

((ClientSettingsSection)ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["applicationSettings"].Sections["MainApplication.Properties.Settings"]).Settings.Get("Tester").Value.ValueXml.InnerText;

Maybe someone can provide a more elegant solition

网友答案:

Since the Settings class is defined on the Main project, you cannot directly access it from the class project because you would create a circular dependency. What you would do is provide the Class library with a delegate it can call to dynamically retrieve the settings from the main project. Create a class that stores a delegate in the Class library and set this delegate to a method defined in the Main project. This methods would encapsulate the instructions needed to retrieve a setting.

And in my opinion, appSettings is not old school, it is just a way of representing configuration parameters that are not specific or customizable by a user.

分享给朋友:
您可能感兴趣的文章:
随机阅读: