0

In my ConfigureServices, I have a number of dependencies configured. The following is repeated many times for different services so only the name of the service and interface name change along with values of some properties.

    services.AddSingleton<IServiceName>(
        client =>
        {
            return new ServiceName(new ServiceInfo
            {
                Url = "http://url"
            });
        });

As this is repeated many times and the URL changes for each service I am wondering if there is some way of doing this in a JSON file.

Hard coding the values means that we have to do a different build for production and using values from app settings for URL would mean creating a setting for each service and calling something like ServiceName.URL which would still be repetition.

Appreciate any ideas on how to achieve a simple solution that would all say 50+ services to be configurable without recompiling the app.

Akif
  • 7,098
  • 7
  • 27
  • 53
AliK
  • 962
  • 2
  • 10
  • 31
  • 1
    Can't you just read the JSON and do a foreach loop on it, adding the services from the file you just read? – Patrick Dec 28 '17 at 16:32
  • Non of the methods take string. As far as I can tell. – AliK Dec 28 '17 at 16:33
  • I assumed you wanted to just change the `Url = "http://url"` portion. – Patrick Dec 28 '17 at 16:34
  • Along with a few other properties that all the services have in common. – AliK Dec 28 '17 at 16:35
  • 1
    If you are "dynamically configuring services", then this question has absolutely nothing to do with DI (the application's composition), but you are instead modifying the runtime state of the application. You most likely need to pass the URL through method parameters of your service from the part of the application that requires it. If not, you should look at using a design pattern to solve the problem, such as [strategy](https://stackoverflow.com/questions/32296209/dependency-injection-unity-conditional-resolving/32415954). – NightOwl888 Dec 29 '17 at 08:27
  • Actually I would say its everything to do with DI as the injection is doing the config for the concrete types. – AliK Dec 29 '17 at 08:57
  • This isn't about dynamic DI or even configuration, as *both* are dynamic. The real question is how to read named configuration objects of the same type. If they were of different types you could register them, eg [using Options](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0). Please post actual examples of the configuration. Are the settings the same? Different? – Panagiotis Kanavos Dec 03 '20 at 13:38
  • It's possible to have [named options too](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0#named-options-support-using-iconfigurenamedoptions) and have each service request the options it wants by name through `IOptionsSnapshot` – Panagiotis Kanavos Dec 03 '20 at 13:40

0 Answers0