Dependency injection

Hi all

Some question about dependency injection. How would i go about injecting a function in to another one to decide whether this function should load sample data/test data or live data.
I heard about partial application. Is that the way to go? In C# one would use interface injection and this decides which interface and in the end which method call to where.

I was thinking, something like …

module sdk
…open models
// this method should execute readdata and then this method knows whether to go to a json file or a rest service to get the data from (i guess these methods would be in other modules (e.g. module restjson, filejson)
…let getProjects (readData: string -> Project list option): Project list option = …

module app
…open sdk
…let readFromFile = filejson.readProjects
…let readFromJson = restjson.readProjects
…let getSampleProjects = sdk.getProjects readFromFile ???
…let getLiveProject = sdk.getProjects readFromJson ???

Not sure if that in any way make sense. I am still learning. Please help me on the way.

If I understand correctly your use case, you can do it by passing to getProjects a function having the specific behaviour, ie loading the projects from a file or from live data. As long as the function signatures are the same, it should work.

You’ll probably be interested in this:

1 Like

That is what i tried but i looks bit different from the examples in your link or others. With that i can inject the functionality. What i dont understand is, that i have to “wrap” my function in a fun to make it work.

let projLoadDeps = (fun _ -> JsonFileService.readProjects)
let lazyProjects = SDK.getProjects projLoadDeps


type readProjects = unit -> Project list option
let getProjects (read:readProjects) : Lazy = …

If I understand correctly this is a function returning a function: (fun _ -> JsonFileService.readProjects). Is that correct and what you want? If it works maybe that’s a good start to investigate.
What’s the type signature of JsonFileService.readProjects ?

This is what I developed for Dependency Injection:

There are some examples in
and also another way of doing it using the Reader monad:

Here is comparison of both methods:

Maybe you’ll find it useful

1 Like

The signature is basically

let readProjects: Project list option=…

it returns a list option. Should it be different to use it as function for injection?

Totally. Really appriciate this option. Let me try that.

Here is an interesting article on the subject:

1 Like

Man, that’s an excellent article. Thanks a lot.