DEV Community

Discussion on: Dependency Injection in F# Web APIs

Collapse
 
amieres profile image
amieres • Edited

Thanks for your post, I find it very interesting and helpful as I still need to learn much of ASP.NET and IoC. Currently for my projects I am using this instead:

github.com/amieres/FsDepend

It is (I believe) a novel approach, and I would very much like to know your opinion, whether you find it useful or not, logical or absurd, pros/cons limitations, etc.

Thanks in advance.

Collapse
 
amieres profile image
amieres • Edited

To mimic your example, this is more or less how it would go:

module Database =
    type Response = Response of string

    let connectionString_  = "connectionString not injected"
    let connectionStringD = Depend.depend0 <@ connectionString_ @>

    let readDataD = Depend.depend {
        let! connectionString = connectionStringD

        return fun (query:string) -> async {
            return [ Response (connectionString + " : " + query) ]
        }
    } 

module Person =
    open Database

    type Person = Person of string

    let getPersonD = Depend.depend {
        let! readData = readDataD

        return fun (personId : string) -> async {
            let query = sprintf "SELECT person FROM Table WHERE id = %s" personId
            match! readData query with
            | [ Response resp ] -> return Some  (Person resp)
            | _-> return None
        }
    } 

module Startup =
    open Database

    let getPerson = 
        Person.getPersonD 
        |> Depend.resolver [ Depend.replace0 <@ connectionString_ @> "dbConnection" ]

    getPerson "111"
    |> Async.RunSynchronously
    |> printfn "%A"

which prints: Some (Person "dbConnection : SELECT person FROM Table WHERE id = 111")