类库可以有 App.config 文件吗?

发布于 2024-10-14 17:34:08 字数 285 浏览 5 评论 0原文

这是我目前的解决方案:

在此处输入图像描述

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

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

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

部署时,输出会将这些 App.config 文件合并为一个文件吗?

Here is what my solution is looking like at the moment:

enter image description here

In the Tutomentor.Branding project, I'd like to save branding information in the App.config file, like names, colors, etc.

In the Tutomentor.Data project, the App.config was created when I added an entity .edmx model file.

Is this possible? Any recommendations?

When deploying, will the output COMBINE these App.config files into a single one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

昇り龍 2024-10-21 17:34:08

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

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

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

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

<?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> 

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

No, class libraries can hold setting files, but their values will be defined in the application configuration (web.config, app.config...).

That's because of configuration settings overriding feature.

You'll need to declare the assemblies' configuration sections in the app.config or web.config of your application (WPF, SL, ASP.NET...) and define a value for a particular number of settings defined in the proper assembly settings.

EDIT:
Add a setting file to your project and add a setting with application scope, and your assembly would have something like this:

<?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> 

Now you'd need to go to your application, and you need to copy-paste the section group, and section declarations, and the definition of the values for the settings. That's all.

執念 2024-10-21 17:34:08

虽然这是一个较旧的线程,但它确实值得重新审视。

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

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

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

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

While this is an older thread, It does warrent another look.

It seems you may want to look at the issue in a different way.

Class libraries by nature are supposed to be portable. So, any configuration needed should be passed to the class, instead of residing with the library. Things like connection strings are by nature transitory, so it makes sense to put them in the owning application.

When utilizing the methods contained in the library, you pass any needed information as part of the method's signature, or as a public property in the class. I suggest you create public properties for your configuration items, and pass them when you instantiate the class.

Now you have no issues with an app.config for the DLL, and the DLL is then truly portable.

离线来电— 2024-10-21 17:34:08

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

Just create your own XML file, name it appConfig.xml or something similar, have your class library read the file using System.Xml instead of System.Configuration, and package the file along with your dll.

血之狂魔 2024-10-21 17:34:08

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

Any specific configuration from library app.config, you have to put in your exe configuration file manually.

極樂鬼 2024-10-21 17:34:08

您可以添加设置文件,它将自动生成 app.config 文件。
Visual C# Items

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

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

You can add Settings File which will automatically generate app.config file.
Visual C# Items

And can Add the key value pairs in tabular form with the datatype specified.
Then Access the values by calling Settings.Default.[KEY]

can reffer: https://www.technical-recipes.com/2018/creating-a-user-settings-class-library-for-your-c-project/

时常饿 2024-10-21 17:34:08

好吧,类库不能有自己的 app.config,但是如果您在 exe 文件的 app.config 中的类库中定义设置,则类库应该能够找到这些设置。

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

Well the class library can't have its own app.config, but if you define your settings the from the class library in the app.config for the exe file the class library should be able to find those to..

im a bit unsure but i don't think it will combine them automatically i guess you have to do i manually!

野心澎湃 2024-10-21 17:34:08

只需使用这个通用配置来处理类库中服务的 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
            });
        }

just use this common config to handle d.injection of services in class lib;

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 file:

{
      "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": "*"

}

//commentout

  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
            });
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文