【问题标题】:Can a class library have an App.config file?类库可以有 App.config 文件吗?
【发布时间】:2011-06-16 13:36:08
【问题描述】:

这是我目前的解决方案的样子:

在 Tutomentor.Branding 项目中,我想将品牌信息保存在 App.config 文件中,例如名称、颜色等。

在 Tutomentor.Data 项目中,App.config 是在我添加实体 .edmx 模型文件时创建的。

这可能吗?有什么建议吗?

部署时,输出会不会将这些 App.config 文件组合成一个文件?

【问题讨论】:

    标签: c# winforms app-config


    【解决方案1】:

    不,类库可以保存设置文件,但它们的值将在应用程序配置(web.config、app.config...)中定义。

    这是因为配置设置覆盖功能。

    您需要在应用程序(WPF、SL、ASP.NET...)的 app.config 或 web.config 中声明程序集的配置部分,并为在正确的装配设置。

    编辑: 将设置文件添加到您的项目并添加具有应用程序范围的设置,您的程序集将具有以下内容:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
                <section name="Assembly1.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
            </sectionGroup>
        </configSections>
        <applicationSettings>
            <Assembly1.Settings1>
                <setting name="settingA" serializeAs="String">
                    <value>a value</value>
                </setting>
            </Assembly1.Settings1>
        </applicationSettings>
    </configuration> 
    

    现在您需要转到您的应用程序,并且需要复制粘贴节组、节声明以及设置值的定义。就这样。

    【讨论】:

    • 你能扩展一下吗?我将如何“在应用程序的 app.config 或 web.config 中声明程序集的配置部分”。
    • 首先在非可执行程序集中创建设置文件,然后在可执行应用程序或 Web 应用程序中重新声明相同的部分,并在那里定义一组设置的值:) 部分的名称(设置文件的命名空间 - 实际上是类 - 必须在程序集和可执行文件中匹配。可执行文件不需要从附属程序集中定义所有设置。您可以定义 1 , 2 或全部。
    • 关于编辑:复制粘贴已经存在的设置听起来是个坏主意。您还有什么建议?
    • 你没有尝试我的解决方案,这是官方的。这不是复制粘贴,而是您在程序集中定义强类型设置,Visual Studio 会为您生成示例 app.config,另一方面,这是将此自动生成的代码复制粘贴到最终代码的快捷方式应用程序可执行配置。
    【解决方案2】:

    虽然这是一个较旧的线程,但它确实值得一看。

    看来您可能想以不同的方式看待这个问题。

    类库本质上应该是可移植的。因此,任何需要的配置都应该传递给类,而不是与库一起驻留。像连接字符串这样的东西本质上是暂时的,所以将它们放在拥有的应用程序中是有意义的。

    使用库中包含的方法时,您可以将任何需要的信息作为方法签名的一部分或作为类中的公共属性传递。我建议您为配置项创建公共属性,并在实例化类时传递它们。

    现在您对 DLL 的 app.config 没有任何问题,并且 DLL 是真正可移植的。

    【讨论】:

    • 我明白你的意思,我同意。但是为什么 Visual Studio 甚至允许为 DLL 创建“Settings.settings”文件呢?微软只是在欺骗我们吗?
    • @Deantwo 这些答案中的大部分信息似乎不再严格准确,至少适用于 Visual Studio 2017。我刚刚创建了一个类库,其中包含一个类的 Settings.settings 文件用作不受我控制的应用程序的插件的库。编译生成了一个library.dll 文件和一个library.dll.config 文件。将这两个文件一起分发,我的插件能够访问自己的设置,而无需以任何方式修改主应用程序的 .config 文件。
    • @jmbpiano 据我所知,这并不完全正确。 VS 2017(和 2013 也是)将创建 library.dll.config 文件,但不会使用它。唯一使用的配置文件是 exe 的。您的设置有效的原因是您的应用使用了在 Settings.Designer.cs 中配置的默认值。如果您尝试在本地(VS 之外)修改库的配置文件,修改将被忽略。
    • @kwitee 谢谢你的澄清。我对我的插件进行了一些测试,你是对的。
    • 对不起,原来的答案还是正确的。将设置从子 app.config 复制到父 web.config。当父应用运行并调用类库,并且该类库引用自己的设置时,父应用将应用 web.config 中的设置。
    【解决方案3】:

    只需创建您自己的 XML 文件,将其命名为 appConfig.xml 或类似名称,让您的类库使用 System.Xml 而不是 System.Configuration 读取该文件,然后将该文件与您的 dll 一起打包。

    【讨论】:

      【解决方案4】:

      库 app.config 中的任何特定配置,您必须手动放入您的 exe 配置文件。

      【讨论】:

        【解决方案5】:

        您可以添加设置文件,它会自动生成 app.config 文件。

        并且可以使用指定的数据类型以表格形式添加键值对。 然后通过调用 Settings.Default.[KEY] 访问这些值

        可以参考:https://www.technical-recipes.com/2018/creating-a-user-settings-class-library-for-your-c-project/

        【讨论】:

          【解决方案6】:

          好吧,类库不能有自己的app.config,但是如果你从app.config中的类库中为exe文件定义你的设置,类库应该能够找到那些......

          我有点不确定,但我认为它不会自动组合它们,我想你必须手动完成!

          【讨论】:

            【解决方案7】:

            只需使用这个通用配置来处理类库中服务的 d.injection;

            public void ConfigureServices(IServiceCollection services)
                    {
                        services.AddDbContext<AppDBContext>(options =>
                        {
                            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                assembly => assembly.MigrationsAssembly(typeof(AppDBContext).Assembly.FullName));
                        });
            
                        services.AddScoped<IUsersRepository, UsersRepository>();
            
                        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                        {
                            builder.AllowAnyOrigin()
                                   .AllowAnyMethod()
                                   .AllowAnyHeader();
                        }));
            
                        // configure strongly typed settings objects
                        var appSettingsSection = Configuration.GetSection("AppSettings");
                        services.Configure<AppSettings>(appSettingsSection);
            
                        // configure jwt authentication
                        var appSettings = appSettingsSection.Get<AppSettings>();
                        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
                        services.AddAuthentication(x =>
                        {
                            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                        })
                        .AddJwtBearer(x =>
                        {
                            x.RequireHttpsMetadata = false;
                            x.SaveToken = true;
                            x.TokenValidationParameters = new TokenValidationParameters
                            {
                                ValidateIssuerSigningKey = true,
                                IssuerSigningKey = new SymmetricSecurityKey(key),
                                ValidateIssuer = false,
                                ValidateAudience = false
                            };
                        });
                        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                    }
            
                    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                    {
                        if (env.IsDevelopment())
                        {
                            app.UseDeveloperExceptionPage();
                        }
                        else
                        {
                            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                            app.UseHsts();
                        }
                        app.UseCors("MyPolicy");
                        app.UseHttpsRedirection();
                        app.UseAuthentication();
                        app.UseMvc();
            
                    }
            

            appsettingjson 文件:

            {
                  "Logging": {
                    "LogLevel": {
                      "Default": "Warning"
                    }
                  },
                  "ConnectionStrings": {
                    "DefaultConnection": "server=.;database=TestAPP;User ID=yener1;password=yener1;"
                  },
                  "AppSettings": {
                    "Secret": "REPLACE THIS WITH YOUR OWN SECRET, IT CAN BE ANY STRING"
                  },
                  "AllowedHosts": "*"
            
            }
            

            //注释掉

              public static class Hasher
                {
                    public static string ToEncrypt<T>(this T value)
                    {
                        using (var sha256 = SHA256.Create())
                        {
                            // Send a sample text to hash.  
                            var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(value.ToString()));
                            // Get the hashed string.  
                            return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                        }
                    }
                }
            public class AppDBContext : DbContext
            {
                public AppDBContext(DbContextOptions options)
                    : base(options)
                {
                }
                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                {
                    base.OnConfiguring(optionsBuilder);
                }
            
                protected override void OnModelCreating(ModelBuilder builder)
                {
                    base.OnModelCreating(builder);
                }
            
                public DbSet<Users> Users { get; set; }
            //BLL
                public class UsersRepository : IUsersRepository
                {
                    private readonly AppDBContext _context;
                    public UsersRepository(AppDBContext context)
                    {
                        _context = context;
                    }
                    public async Task<IEnumerable<Users>> GetUsers()
                    {
                        return await _context.Users.ToListAsync();
                    }
            
            
            [AllowAnonymous]
                    [HttpPost("authenticate")]
                    public IActionResult Authenticate([FromBody]UserDto userDto)
                    {
                        var user = _userService.Authenticate(userDto.Username, userDto.Password);
            
                        if (user == null)
                            return BadRequest("Username or password is incorrect");
            
                        var tokenHandler = new JwtSecurityTokenHandler();
                        var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[] 
                            {
                                new Claim(ClaimTypes.Name, user.Id.ToString())
                            }),
                            Expires = DateTime.UtcNow.AddDays(7),
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token = tokenHandler.CreateToken(tokenDescriptor);
                        var tokenString = tokenHandler.WriteToken(token);
            
                        // return basic user info (without password) and token to store client side
                        return Ok(new {
                            Id = user.Id,
                            Username = user.Username,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            Token = tokenString
                        });
                    }
            

            【讨论】:

              猜你喜欢
              • 2011-07-17
              • 2011-06-04
              • 2011-07-02
              • 2011-05-21
              • 2015-10-24
              • 2011-05-14
              • 2011-03-09
              • 2010-11-01
              • 1970-01-01
              相关资源
              最近更新 更多