Giraffe: Question: configuration settings

Created on 12 May 2017  路  9Comments  路  Source: giraffe-fsharp/Giraffe

How would one get a configuration setting, say a connectionstring inside a HttpContextHandler?
Is it possible to get the IConfiguration from HttpContext.RequestServices? I'm less familiar with this.

Most helpful comment

All 9 comments

You could do something like this:

let someHander () =
    fun (ctx : HttpHandlerContext) ->
        async {
            let dbConfig = ctx.Services.GetService<IOptions<MyDbConfig>>()
            let dbConnectionString = dbConfig.ConnectionString
            // your code here
            return! ctx
        }

You can read about configuration and IOptions with DI here, which will explain how you get IOptions<MyDbConfig> registered.

You could use the HttpContext.RequestService but Giraffe already has an IServiceProvider on the HttpHandlerContext, I'd be interested to know who we couldn't just recommend the usage of HttpContext.RequestService. @dustinmoris ?

Using the IServiceProvider from the HttpContext would make sense, was it always there? If yes then I must have missed it o.0

Could the ILogger not be fetched from the HttpContext.RequestService as well?
Would it not make sense to transition from the HttpHandlerContext to the HttpContext?
If there a function getLogger, that might suffice as well

let getLogger (ctx: HttpContext) =
    ctx.RequestService<ILogger>()

let myHandler() =
    fun (ctx: HttpContext) ->
        async {
              let logger = getLogger ctx
             // do loggin
            return! ctx
        }

It would be a big change, but given this is pre 1.0 that makes a lot of sense. @dustinmoris ?

Now that you say that it is actually such an obvious change :). I am working on it (This is why I am hesitant to declare this library 1.0 too early, thanks!).

What's your opinion on helper method vs. extension method:

type HttpContext with
    member this.GetService<'T>() =
        this.RequestServices.GetService(typeof<'T>) :?> 'T

    member this.GetLogger<'T>() =
        this.GetService<ILogger<'T>>()

Hmm, interesting. Extensions might be a better fit here.

Ok cool, I had the same feeling, but wanted to get at least a second opinion.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dustinmoris picture dustinmoris  路  7Comments

rmunn picture rmunn  路  6Comments

Disco-Dave picture Disco-Dave  路  4Comments

Dzoukr picture Dzoukr  路  4Comments

dustinmoris picture dustinmoris  路  6Comments