Using appsettings in the DAL layer

2019-03-30 04:17发布

I have a winforms application in which some of the data is stored in XML files. The location where these XML files should be stored can be configured by the user, and is stored in the AppSettings. All my layers are separate assemblies. Can I access my settings from my DAL assembly, or should I pass this as an argument through all my layers?

When I try to read the settings from my DAL layer, I encounter another problem

        Configuration config = ConfigurationManager.OpenExeConfiguration(
            System.Reflection.Assembly.GetEntryAssembly().Location);
        string dataStorageLocation = config.AppSettings["DataStorageLocation"];

config.AppSettings["DataStorageLocation"] gives a compilation error: System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty] is inaccessible due to its protection level. Why is that?

Can someone put me on the right track? Thanks.

2条回答
Summer. ? 凉城
2楼-- · 2019-03-30 05:05

You need to use config.AppSettings.Settings["DataStorageLocation"]. See the MSDN documentation for a sample.

Alternatively, and IMHO better, you could use System.Configuration.ConfigurationManager.AppSettings[name] to access the AppSettings of the host application. This is probably more flexible than your technique, as it will also work if your DAL assembly is, for example, hosted in a service tier on IIS. Accessing configuration information from the host application's configuration file directly in this way is perfectly accceptable, and generally better than passing configuration information down through the layers.

查看更多
太酷不给撩
3楼-- · 2019-03-30 05:06

The AppSettings are accessible to any assembly loaded by the calling process, so you will have no problems accessing them with any assembly you load.

查看更多
登录 后发表回答