简体   繁体   中英

How to store configuration information in a .net Standard project

There appears to be no configuration app.config or web.config in .net Standard. Where can settings like Url, ids etc be stored in the .net Standard class library project.

The project is self contained, and abstracts information from the implementer. It is a client, and the app using it does not need to configure the endpoints it hits.

You cannot add an app.config file to a class library project without some bending and twisting on your part. Also it does not make any sense to add config to your library. instead add the config to the project which is using your library.

Class libraries generally don't have configs so they can adapt to the configs provided from the calling project.

Tying a class library directly to a configuration file makes it difficult to be able to override that configuration in code. Many libraries that were made in .NET Framework suffered from this problem, which became most painful when trying to configure a library using modern dependency injection techniques. Microsoft has intentionally made this more difficult to do in .NET Standard.

Rather than configuring a modern library using files, you should aim to allow configuration to be passed in through object constructors, just like any other dependency. If you have configuration URLs that have a logical default, then you can simply put those defaults into your configuration objects.

public class MyClassConfiguration
{
    public string Url { get; set; } = "https://example.com/some-default-location";
}

One way to make this easy for the consumer of your library to swallow is to create your business logic in DI-friendly constructor injected classes, then make some facade classes that are meant specifically for constructing them and supplying default values. A good way of getting this done is to use a fluent builder pattern as described in Mark Seemann's DI-Friendly Library post .

var foo =
   new FooBuilder().WithUrl("https://example.com/override-the-default").Create();

It can then be up to the consumer of your library whether to keep the configuration as code or read it from a configuration file and pass it to your library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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