Giraffe: [Question] How to use dependency injection?

Created on 10 Oct 2017  路  4Comments  路  Source: giraffe-fsharp/Giraffe

I was playing with signalr core (alpha2) and just figured out that there is no GlobalHost class, so, this SO answer shows the new way to do that.

How do I get the IHubContext injected by .net core's DI on, say, my function?

alert: this compile but the client never get the message...

    let smallHandler =
        fun (next : HttpFunc) (ctx : HttpContext) ->
            task {                    
                    let lifeManager = new DefaultHubLifetimeManager<AgentHub>()
                    let hub = new SignalR.HubContext<AgentHub>(lifeManager)    
                    do! hub.Clients.All.InvokeAsync("saludar", "hola, mundo")                    
                    return! (redirectTo false "/") next ctx
            }

Thank you 馃嵒

Most helpful comment

Can use use ctx.GetService<IHubContext<AgentHub>>() ?

All 4 comments

Can use use ctx.GetService<IHubContext<AgentHub>>() ?

Jon is right, just make sure its set up in application services just like in c# version.

on an unrelated topic ...

         hub.Clients.All.InvokeAsync("saludar", "hola, mundo")
         |> Async.AwaitTask
         |> Async.RunSynchronously

InvokeAsync is an async task so all that can be removed ... and is encouraged as your locking up thread with this method, killing throughput.

You could also probably take the redirectTo out of the function and pipe it on the end of your pipeline so that instead you can use the standard continuation of return! next ctx (next being your redirectTo.

your example could be rewritten as

let smallHandler : HttpHandler=
      fun next ctx ->
          task {
                let lifeManager = new DefaultHubLifetimeManager<AgentHub>()
                let hub = new SignalR.HubContext<AgentHub>(lifeManager)    
                do! hub.Clients.All.InvokeAsync("saludar", "hola, mundo")     // << task async await
                return! next ctx
            }
let app = smallHandler >=> redirectTo false "/"

@JonCanning yup! you are right! thank you!

@gerardtoconnor yeah, I updated the sample before any answer... you caught me on my mistake 馃槼

thank you again guys

Was this page helpful?
0 / 5 - 0 ratings