简体   繁体   English

app.config用于类库

[英]app.config for a class library

I cannot see a app.config file generated for a class library by the VS2008 wizard. 我看不到VS2008向导为类库生成的app.config文件。 In my research I found that in an application only one app.config exists. 在我的研究中,我发现在应用程序中只存在一个app.config。

Is it a bad thing to add an app.config manually to a class library or are there any other methods which will serve the purpose of an app.config in class library? 将app.config手动添加到类库中是否是一件坏事,还是有任何其他方法可以满足类库中app.config的用途?

I need to store log4net config information inside the app.config file. 我需要在app.config文件中存储log4net配置信息。

You generally should not add an app.config file to a class library project; 通常不应添加app.config文件到一个类库项目; it won't be used without some painful bending and twisting on your part. 没有一些痛苦的弯曲和扭曲你将不会使用它。 It doesn't hurt the library project at all - it just won't do anything at all. 它根本不会伤害图书馆项目 - 它根本不会做任何事情。

Instead, you configure the application which is using your library; 而是配置使用您的库的应用程序; so the configuration information required would go there. 所以所需的配置信息会去那里。 Each application that might use your library likely will have different requirements, so this actually makes logical sense, too. 可能使用您的库的每个应用程序可能会有不同的要求,因此这实际上也具有逻辑意义。

I don't know why this answer hasn't already been given: 我不知道为什么还没有给出这个答案:

Different callers of the same library will, in general, use different configurations. 通常,同一库的不同调用者将使用不同的配置。 This implies that the configuration must reside in the executable application, and not in the class library. 这意味着配置必须驻留在可执行应用程序中,而不是类库中。

You may create an app.config within the class library project. 您可以在类库项目中创建app.config。 It will contain default configurations for items you create within the library. 它将包含您在库中创建的项目的默认配置。 For instance, it will contain connection strings if you create an Entity Framework model within the class library. 例如,如果在类库中创建实体框架模型,它将包含连接字符串。

However, these settings will not be used by the executable application calling the library. 但是,调用库的可执行应用程序不会使用这些设置。 Instead, these settings may be copied from the library.dll.config file into the app.config or web.config of the caller, so that they may be changed to be specific to the caller, and to the environment into which the caller is deployed. 相反,可以将这些设置从library.dll.config文件复制到调用方的app.config或web.config中,以便可以将它们更改为特定于调用方以及调用方所属的环境。部署。

This is how it has been with .NET since Day 1. 这是第1天以来.NET的用法。

Jon, a lot of opinion has been given that didn't correctly answer your question. Jon,很多意见都没有正确回答你的问题。

I will give MY OPINION and then tell you how to do exactly what you asked for. 我会给出我的意见,然后告诉你如何做到你所要求的。

I see no reason why an assembly couldn't have its own config file. 我认为没有理由为什么程序集不能拥有自己的配置文件。 Why is the first level of atomicy (is that a real word?) be at the application level? 为什么第一级的atomicy(是真正的单词?)在应用程序级别? Why not at the solution level? 为什么不在解决方案级别? It's an arbitrary, best-guess decision and as such, an OPINION. 这是一个任意的,最佳猜测的决定,因此,一个意见。 If you were to write a logging library and wanted to include a configuration file for it, that would be used globally, why couldn't you hook into the built-in settings functionality? 如果你要编写一个日志库并希望为它包含一个配置文件,那么它将全局使用,为什么你不能挂入内置设置功能? We've all done it ... tried to provide "powerful" functionality to other developers. 我们都做到了......试图为其他开发者提供“强大”的功能。 How? 怎么样? By making assumptions that inherently translated to restrictions. 通过做出本质上转化为限制的假设。 That's exactly what MS did with the settings framework, so you do have to "fool it" a little. 这正是MS对设置框架所做的,所以你必须“愚弄”一点。

To directly answer your question, simply add the configuration file manually (xml) and name it to match your library and to include the "config" extension. 要直接回答您的问题,只需手动添加配置文件(xml)并将其命名为与您的库匹配,并包含“config”扩展名。 Example: 例:

MyDomain.Mylibrary.dll.Config MyDomain.Mylibrary.dll.Config

Next, use the ConfigurationManager to load the file and access settings: 接下来,使用ConfigurationManager加载文件和访问设置:

string assemblyPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
Configuration cfg = ConfigurationManager.OpenExeConfiguration(assemblyPath);
string result = cfg.AppSettings.Settings["TEST_SETTING"].Value;

Note that this fully supports the machine.config heierarchy, even though you've explicitly chosen the app config file. 请注意,即使您已明确选择了应用程序配置文件,这也完全支持machine.config层次结构。 In other words, if the setting isn't there, it will resolve higher. 换句话说,如果设置不存在,它将解决更高的问题。 Settings will also override machine.config entries. 设置还将覆盖machine.config条目。

If you want to configure your project logging using log4Net, while using a class library, There is no actual need of any config file. 如果要使用log4Net配置项目日志记录,则在使用类库时,实际上不需要任何配置文件。 You can configure your log4net logger in a class and can use that class as library. 您可以在类中配置log4net记录器,并可以将该类用作库。

As log4net provides all the options to configure it. 由于log4net提供了配置它的所有选项。

Please find the code below. 请在下面找到代码。

public static void SetLogger(string pathName, string pattern)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = pattern;
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = pathName;
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "1GB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            MemoryAppender memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = log4net.Core.Level.Info;
            hierarchy.Configured = true;
      }

Now instead of calling XmlConfigurator.Configure(new FileInfo("app.config")) you can directly call SetLogger with desired path and pattern to set the logger in Global.asax application start function. 现在,您可以直接使用所需的路径和模式调用SetLogger,而不是调用XmlConfigurator.Configure(新的FileInfo(“app.config”)),以在Global.asax应用程序启动函数中设置记录器。

And use the below code to log the error. 并使用以下代码记录错误。

        public static void getLog(string className, string message)
        {
            log4net.ILog iLOG = LogManager.GetLogger(className);
            iLOG.Error(message);    // Info, Fatal, Warn, Debug
        }

By using following code you need not to write a single line neither in application web.config nor inside the app.config of library. 通过使用以下代码,您无需在应用程序web.config中或库的app.config内部写入单行。

In fact, the class library you are implementing, is retrieving information from app.config inside the application that is consuming it, so, the most correct way to implement configuration for class libraries at .net in VS is to prepare app.config in the application to configure everything it consumes, like libraries configuration. 实际上,您正在实现的类库是从正在使用它的应用程序内的app.config中检索信息,因此,在VS中.net中实现类库的配置的最正确方法是准备app.config 。应用程序来配置它消耗的所有内容,例如库配置。

I have worked a little with log4net, and I found that the one who prepared the application always had a section for log4net configuration inside main app.config . 我已经使用log4net做了一点工作,我发现准备应用程序的人总是在主app.config中有一个用于log4net配置的部分。

I hope you find this information useful. 我希望这个信息对您有所帮助。

See you, and post comments about the solution you found. 见到你,发表关于你找到的解决方案的评论。

EDIT: 编辑:

At the next link you have an app.config with the section for log4net: 在下一个链接中,您有一个app.config ,其中包含log4net的部分:

http://weblogs.asp.net/tgraham/archive/2007/03/15/a-realistic-log4net-config.aspx http://weblogs.asp.net/tgraham/archive/2007/03/15/a-realistic-log4net-config.aspx

Actually, for some rare case you could store app.config in class libraries (by adding manually) and parse it by OpenExeConfiguration . 实际上,对于一些罕见的情况,您可以在类库中存储app.config(通过手动添加)并通过OpenExeConfiguration解析它。

 var fileMap =
    new ExeConfigurationFileMap {ExeConfigFilename = 
    @"C:\..somePath..\someName.config"};
 System.Configuration.Configuration config =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    ConfigurationUserLevel.None);

You should really estimate the real need of this. 你应该真的估计这个的真正需要。 For abstract data its not the best solution, but "Config Sections" could be very usefull!! 对于抽象数据,它不是最好的解决方案,但“Config Sections”可能非常有用!!

For example, we organised our N-Tier WCF architecture decoupled, without any metadata, simply by using Unity Container and Injection Factory based on Channel Factory T. We added externall ClassLibrary dll with just [Service Contract] Interfaces and common app.config in order to read endpoints from clientsection, and easily add/change them at one place. 例如,我们只使用基于Channel Factory T的Unity容器和注入工厂组织我们的N层TCF分离,没有任何元数据。我们添加了外部ClassLibrary dll,只有[Service Contract]接口和常见的app.config按顺序从clientsection读取端点,并在一个地方轻松添加/更改它们。

You do want to add App.config to your tests class library, if you're using a tracer/logger. 如果您正在使用跟踪器/记录器,则需要将App.config添加到测试类库中。 Otherwise nothing gets logged when you run the test through a test runner such as TestDriven.Net. 否则,当您通过TestDriven.Net等测试运行器运行测试时, 不会记录任何内容

For example, I use TraceSource in my programs, but running tests doesn't log anything unless I add an App.config file with the trace/log configuration to the test class library too. 例如,我在我的程序中使用TraceSource ,但运行测试不会记录任何内容,除非我将带有跟踪/日志配置的App.config文件添加到测试类库中。

Otherwise, adding App.config to a class library doesn't do anything. 否则,将App.config添加到类库不会执行任何操作。

Your answer for a non manual creation of an app.config is Visual Studio Project Properties/Settings tab. 非手动创建app.config的答案是Visual Studio项目属性/设置选项卡。

When you add a setting and save, your app.config will be created automatically. 添加设置并保存时,将自动创建app.config。 At this point a bunch of code is generated in a { yourclasslibrary .Properties} namespace containing properties corresponding to your settings. 此时,在{ yourclasslibrary .Properties }命名空间中生成一堆代码,其中包含与您的设置对应的属性。 The settings themselves will be placed in the app.config's applicationSettings settings. 设置本身将放在app.config的applicationSettings设置中。

 <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <section name="ClassLibrary.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
</configSections>
<applicationSettings>
    <ClassLibrary.Properties.Settings>
        <setting name="Setting1" serializeAs="String">
            <value>3</value>
        </setting>
    </BookOneGenerator.Properties.Settings>
</applicationSettings>

If you added an Application scoped setting called Setting1 = 3 then a property called Setting1 will be created. 如果添加了名为Setting1 = 3的应用程序作用域设置,则将创建名为Setting1的属性。 These properties are becoming at compilation part of the binary and they are decorated with a DefaultSettingValueAttribute which is set to the value you specified at development time. 这些属性正在成为二进制文件的编译部分,它们使用DefaultSettingValueAttribute进行修饰,该设置为您在开发时指定的值。

     [ApplicationScopedSetting]
    [DebuggerNonUserCode]
    [DefaultSettingValue("3")]
    public string Setting1
    {
        get
        {
            return (string)this["Setting1"];
        }
    }

Thus as in your class library code you make use of these properties if a corresponding setting doesn't exist in the runtime config file, it will fallback to use the default value. 因此,如果在类库代码中使用这些属性,如果运行时配置文件中不存在相应的设置,则它将回退使用默认值。 That way the application won't crash for lacking a setting entry, which is very confusing first time when you don't know how these things work. 这样,由于缺少设置条目,应用程序不会崩溃,这在您不知道这些工作如何工作时第一次非常混乱。 Now, you're asking yourself how can specify our own new value in a deployed library and avoid the default setting value be used? 现在,您问自己如何在已部署的库中指定我们自己的新值并避免使用默认设置值?

That will happen when we properly configure the executable's app.config. 当我们正确配置可执行文件的app.config时会发生这种情况。 Two steps. 两个步骤。 1. we make it aware that we will have a settings section for that class library and 2. with small modifications we paste the class library's config file in the executable config. 1.我们让它意识到我们将为该类库设置一个设置部分.2。通过小修改,我们将类库的配置文件粘贴到可执行配置中。 (there's a method where you can keep the class library config file external and you just reference it from the executable's config. (有一种方法可以将类库配置文件保存在外部,您只需从可执行文件的配置中引用它。

So, you can have an app.config for a class library but it's useless if you don't integrate it properly with the parent application. 因此,您可以为类库提供app.config,但如果您没有将其与父应用程序正确集成,则它无用。 See here what I wrote sometime ago: link 在这里看到我之前写的东西: 链接

There is no automatic addition of app.config file when you add a class library project to your solution. 将类库项目添加到解决方案时,不会自动添加app.config文件。

To my knowledge, there is no counter indication about doing so manualy. 据我所知,没有关于这样做的反制迹象。 I think this is a common usage. 我认为这是一种常见的用法。

About log4Net config, you don't have to put the config into app.config, you can have a dedicated conf file in your project as well as an app.config file at the same time. 关于log4Net配置,您不必将配置放入app.config,您可以在项目中同时拥有专用的conf文件以及app.config文件。

this link http://logging.apache.org/log4net/release/manual/configuration.html will give you examples about both ways (section in app.config and standalone log4net conf file) 此链接http://logging.apache.org/log4net/release/manual/configuration.html将为您提供有关这两种方式的示例(app.config中的部分和独立的log4net conf文件)

I would recommend using Properties.Settings to store values like ConnectionStrings and so on inside of the class library. 我建议使用Properties.Settings来存储类库中的ConnectionStrings等值。 This is where all the connection strings are stores in by suggestion from visual studio when you try to add a table adapter for example. 当您尝试添加表适配器时,这是所有连接字符串通过visual studio的建议存储的位置。 enter image description here 在此输入图像描述

And then they will be accessible by using this code every where in the clas library 然后,可以通过在clas库中的每个位置使用此代码来访问它们

var cs=  Properties.Settings.Default.[<name of defined setting>];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM