SaturnFramework / Saturn

Opinionated, web development framework for F# which implements the server-side, functional MVC pattern
https://saturnframework.org
MIT License
708 stars 108 forks source link

Configure services from a config file #202

Closed MarneeDear closed 4 years ago

MarneeDear commented 4 years ago

I need to manually configure a service based on some things in my config file. I tried to access the config file during startup in the function that is called by service_config, but I can't access the config file. My config is in appsettings.json

How can I access my config in services_config at startup? Is this possible?

This is what I have tried. In configureServices I try to instantiate an httpContext, but it is null

let configureServices (services : IServiceCollection) =    
    let ctx = HttpContextAccessor()
    let config = ctx.HttpContext.GetService<IConfiguration>()
    :                        //^^this is null ^^
    :

let app = application {
    :
    service_config configureServices
    :
}
baronfel commented 4 years ago

So there's not a request incoming at startup, which is why you get the null there. At startup, if you want to access your configuration, you'll have to call services.Build() to get an IServiceProvider, which you can then use to call Getservice as you did in your example.

MarneeDear commented 4 years ago

Thanks @baronfel . That worked. I did it like this:

let configureServices (services : IServiceCollection) =  
    let sp = services.BuildServiceProvider()
    let config = sp.GetService<IConfiguration>()
mastoj commented 4 years ago

That's a nice work around, but maybe the configuration should be an argument to configureServices so you don't have to build the provider on startup. Or is there a good reason to why that isn't the case.

Krzysztof-Cieslak commented 4 years ago

@mastoj, the big question is how it should be handled in general. Should it be added in all custom operations in application CE? Should it be added as overloads (which are not working super well with CEs)? Should we provide new custom operations accepting additionally config? Or maybe should we create runWithConfig? That will take 'Config -> Application instead of just Application as current run

There are lot of different options here, and I haven’t figured out good design yet. Suggestions and PRs are welcomed 😀

Krzysztof-Cieslak commented 4 years ago

Currently open issue touching config issue is here https://github.com/SaturnFramework/Saturn/issues/223