.NET 3,5 DLL с помощью его собственного файла конфигурации

Это - известная ошибка в Java 1.4: http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087

Это фиксируется в Java 1.5, но Sun не намеревается зафиксировать его в 1,4.

проблема - то, что, во время создания, Thread добавляется к списку ссылок во внутренней таблице потока. Это не будет удалено из того списка до своего запуска (), метод завершился. Пока та ссылка там, она не будет собрана "мусор".

Так, никогда не создавайте поток, если Вы определенно не собираетесь назвать start() метод. Thread объект run() метод нельзя назвать непосредственно.

А лучший способ кодировать его состоит в том, чтобы реализовать эти Runnable интерфейс, а не подкласс Thread. Когда Вам не нужен поток, звоните

myRunnable.run();

при необходимости в потоке:

Thread myThread = new Thread(myRunnable);
myThread.start();

6
задан user31673 9 October 2009 в 14:46
поделиться

4 ответа

Система конфигурации .NET 2.0 и выше предоставляет вам возможности - вы можете, например, загрузить определенный файл конфигурации по запросу. Это немного больше работы, но это работает.

Вам нужно будет сделать что-то вроде этого:

// set up a exe configuration map - specify the file name of the DLL's config file
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "ConfigLibrary.config";

// now grab the configuration from the ConfigManager
Configuration cfg = ConfigurationManager
                   .OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

// now grab the section you're interested in from the opened config - 
// as a sample, I'm grabbing the <appSettings> section
AppSettingsSection section = (cfg.GetSection("appSettings") as AppSettingsSection);

// check for null to be safe, and then get settings from the section
if(section != null)
{
   string value = section.Settings["Test"].Value;
}

Вам также необходимо убедиться, что конфигурация для библиотеки классов DLL создается и копируется в место, где вы может добраться до этого. В худшем случае вам нужно указать конкретный файл конфигурации и убедиться, что он копируется в выходной каталог, установив его свойство «Копировать в выходной каталог» в окне свойств Visual Studio.

Вам также следует ознакомиться с трехчастным разделом Джона Ристы. серия по настройке .NET 2.0 на CodeProject.

5
ответ дан 17 December 2019 в 00:11
поделиться

Generally when you have settings at the application level, you need to generate those settings at the application level, and then percolate them through your libraries. It adds a few more lines of code to your initialization to inject dependencies, but you are essentially trying to do that anyway.

You are going to run into way more problems than its worth if you try to include a config file for just the dll side by side with every deployment of your library, and it just doesn't make a lot of sense semantically.

Take System.Data for example...when you create a connection, you specify the connection string, not create a separate config file for just the connection string to deploy side by side with the System.Data library. [and that would cause tons of problems since it likely resides in the GAC on your system anyway]

1
ответ дан 17 December 2019 в 00:11
поделиться

You cannot use the built-in .Net configuration system to do this. It is designed (as it should be ) to configure application processes, not indvidual Dlls. The correct way to go about this is to add the configuration settings for the dll into the app.config system for each executable application that "uses" (has a reference to) that dll. (or in the machine.config)

  • Simply making the settings accessible to ALL applictions that uset he dll can be accomplished by putting them in the Machine.config (in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG for .Net2.0

If you don't want to do it that way, then you will have to write your own code to open, read, and write frm a custom Xml file, (or whatever format you choose to use) to extyract those settings.

1
ответ дан 17 December 2019 в 00:11
поделиться

The easiest answer to this would be to put the values in the machine.config. That way all apps using the dll will be able to access the information through the .net app configuration classes. With this way too, if you absolutely need to override a value for a certain applicatin, you can override it in the main application's app.config file.

0
ответ дан 17 December 2019 в 00:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: