Repository F# setup
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Layers
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.PlatformService
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScriptChoosing an Approach
Axial has one dependency model: workflows read an explicit environment, reusable helpers name service contracts, and layers build the environment at the boundary.
Use this order:
- Use records plus
Flow.envWithfor most application code. - Declare a per-service contract for reusable named services.
- Use
LayerandLayer.provideto build environments and own resource cleanup. - Use
ServiceProvider.getonly at .NET host edges where directIServiceProviderlookup is intentional.
Default Shape
Plain F# records are the default recommendation because they are legible, easy to fake in tests, and easy to refactor.
Shared setup
// Setup for the checked examples on this page.
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Layers
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.PlatformService
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScript
/// Fails the docs test when an example's result differs from the value shown.
let shouldEqual expected actual =
if actual <> expected then failwithf "Expected %A but got %A" expected actual
SystemIOThreadingTasksAxialLayersConsoleFileSystemHostingBrowserNodePlatformServiceStateTelemetryJavaScriptshouldEqual: 'a -> 'a -> unitexpected: 'aactual: 'a(<>): 'T -> 'T -> boolStructural inequality The first parameter. The second parameter. The result of the comparison. 5 <> 5 // Evaluates to false 5 <> 6 // Evaluates to true [1; 2] <> [1; 2] // Evaluates to false
failwithf: Printf.StringFormat<'T,'Result> -> 'TPrint to a string buffer and raise an exception with the given result. Helper printers must return strings. The formatter. The formatted result. See Printf.failwithf (link: ) for examples.
type Order = { Id: int }
type OrderError = DuplicateOrder of int
type IOrderRepo =
abstract Save: Order -> Result<unit, OrderError>
type IEmailSender =
abstract SendConfirmation: Order -> unit
type ApiDeps = { Orders: IOrderRepo; Email: IEmailSender }
let placeOrder (order: Order) : Flow<ApiDeps, OrderError, unit> =
flow {
let! orders = Flow.envWith _.Orders
let! email = Flow.envWith _.Email
do! orders.Save order
email.SendConfirmation order
}
FsLiveDocsGeneratedPage16_4556FC416C2B.OrderId: intintAn abbreviation for the CLI type . Basic Types
FsLiveDocsGeneratedPage16_4556FC416C2B.OrderErrorDuplicateOrderFsLiveDocsGeneratedPage16_4556FC416C2B.IOrderRepoSave: IOrderRepo -> Order -> Result<unit,OrderError>Microsoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
FsLiveDocsGeneratedPage16_4556FC416C2B.IEmailSenderSendConfirmation: IEmailSender -> Order -> unitFsLiveDocsGeneratedPage16_4556FC416C2B.ApiDepsOrders: IOrderRepoEmail: IEmailSenderplaceOrder: Order -> Flow<ApiDeps,OrderError,unit>order: OrderAxial.Flow`3Represents a cold workflow that reads an environment, returns a typed result, and is executed explicitly through one of its execution members such as ToTask, ToAsync, or RunSynchronously. The type of the environment dependency. The type of the failure value. The type of the success value.
flow: FlowBuilderThe universal flow { } computation expression.
orders: IOrderRepoAxial.FlowenvWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let currentTime () = Flow.envWith (fun (environment: BaseRuntime) -> environment.Clock.UtcNow())
_arg1: ApiDepsemail: IEmailSender_arg3: ApiDepsSave: Order -> Result<unit,OrderError>SendConfirmation: Order -> unitA test supplies the same record with fakes:
type MemoryOrders() =
let saved = ResizeArray<int>()
member _.Saved = List.ofSeq saved
interface IOrderRepo with
member _.Save order =
if saved.Contains order.Id then
Error(DuplicateOrder order.Id)
else
saved.Add order.Id
Ok()
type MemoryEmail() =
let sent = ResizeArray<int>()
member _.Sent = List.ofSeq sent
interface IEmailSender with
member _.SendConfirmation order = sent.Add order.Id
FsLiveDocsGeneratedPage16_4556FC416C2B.MemoryOrderssaved: ResizeArray<int>``.ctor``: unit -> unitInitializes a new instance of the class that is empty and has the default initial capacity.
intAn abbreviation for the CLI type . Basic Types
_: MemoryOrdersSaved: MemoryOrders -> unit -> int listMicrosoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
ofSeq: 'T seq -> 'T listBuilds a new list from the given enumerable object. The input sequence. The list of elements from the sequence. let inputs = seq { 1; 2; 5 } inputs |> List.ofSeq Evaluates to [ 1; 2; 5 ]. This is an O(n) operation, where n is the length of the sequence.
FsLiveDocsGeneratedPage16_4556FC416C2B.IOrderRepoSave: MemoryOrders -> Order -> Result<unit,OrderError>order: OrderContains: int -> boolDetermines whether an element is in the . The object to locate in the . The value can be for reference types. if is found in the ; otherwise, .
Id: intErrorRepresents an Error or a Failure. The code failed with a value of 'TError representing what went wrong.
DuplicateOrderAdd: int -> unitAdds an object to the end of the . The object to be added to the end of the . The value can be for reference types.
OkRepresents an OK or a Successful result. The code succeeded with a value of 'T.
FsLiveDocsGeneratedPage16_4556FC416C2B.MemoryEmailsent: ResizeArray<int>_: MemoryEmailSent: MemoryEmail -> unit -> int listFsLiveDocsGeneratedPage16_4556FC416C2B.IEmailSenderSendConfirmation: MemoryEmail -> Order -> unitlet orders = MemoryOrders()
let email = MemoryEmail()
let deps = { Orders = orders; Email = email }
placeOrder { Id = 1 } |> Flow.run deps |> shouldEqual (Exit.Success())
placeOrder { Id = 1 } |> Flow.run deps |> shouldEqual (Exit.Failure(Cause.Fail(DuplicateOrder 1)))
email.Sent |> shouldEqual [ 1 ]
orders: MemoryOrders``.ctor``: unit -> MemoryOrdersemail: MemoryEmail``.ctor``: unit -> MemoryEmaildeps: ApiDepsOrders: IOrderRepoEmail: IEmailSenderplaceOrder: Order -> Flow<ApiDeps,OrderError,unit>Id: int(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Axial.Flowrun: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
shouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
FailureThe workflow failed due to a specific cause.
Axial.Cause`1Represents the cause of a failed workflow. The type of the domain-specific failure value.
FailAn expected domain-specific failure.
DuplicateOrderSent: int listUse a concrete record for the boundary. Add a named abstraction only when more than one implementation or caller needs it.
Service Contracts
Reusable helpers can ask for a named service without forcing every application to use the same record shape:
type IHasOrders =
abstract OrderRepo: IOrderRepo
let orderRepo<'env, 'error when 'env :> IHasOrders> : Flow<'env, 'error, IOrderRepo> =
Flow.envWith _.OrderRepo
let save (order: Order) : Flow<#IHasOrders, OrderError, unit> =
flow {
let! orders = orderRepo
do! orders.Save order
}
FsLiveDocsGeneratedPage16_4556FC416C2B.IHasOrdersOrderRepo: IHasOrders -> unit -> IOrderRepoFsLiveDocsGeneratedPage16_4556FC416C2B.IOrderRepoorderRepo: Flow<'env,'error,IOrderRepo>enverrorAxial.Flow`3Represents a cold workflow that reads an environment, returns a typed result, and is executed explicitly through one of its execution members such as ToTask, ToAsync, or RunSynchronously. The type of the environment dependency. The type of the failure value. The type of the success value.
Axial.FlowenvWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let currentTime () = Flow.envWith (fun (environment: BaseRuntime) -> environment.Clock.UtcNow())
_arg1: 'envOrderRepo: IOrderReposave: Order -> Flow<'a,OrderError,unit>order: OrderFsLiveDocsGeneratedPage16_4556FC416C2B.OrderFsLiveDocsGeneratedPage16_4556FC416C2B.OrderErrorunitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
flow: FlowBuilderThe universal flow { } computation expression.
orders: IOrderRepoSave: Order -> Result<unit,OrderError>Any environment that implements IHasOrders can run save:
type CheckoutEnv =
{ Orders: IOrderRepo }
interface IHasOrders with
member this.OrderRepo = this.Orders
FsLiveDocsGeneratedPage16_4556FC416C2B.CheckoutEnvOrders: IOrderRepoFsLiveDocsGeneratedPage16_4556FC416C2B.IOrderRepoFsLiveDocsGeneratedPage16_4556FC416C2B.IHasOrdersthis: CheckoutEnvOrderRepo: CheckoutEnv -> unit -> IOrderReposave { Id = 7 } |> Flow.run { Orders = MemoryOrders() } |> shouldEqual (Exit.Success())
save: Order -> Flow<'a,OrderError,unit>Id: int(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Axial.Flowrun: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
Orders: IOrderRepo``.ctor``: unit -> MemoryOrdersshouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
Layers
Layers build explicit environments and own cleanup through Scope. Use layer { } when application startup needs to
combine several services into one environment.
type AppEnv = { Runtime: BaseRuntime; Orders: IOrderRepo }
let ordersLayer : Layer<unit, OrderError, IOrderRepo> = Layer.succeed (MemoryOrders())
let appLayer : Layer<unit, OrderError, AppEnv> =
layer {
let! runtime = BaseRuntime.live |> Layer.widenError
and! orders = ordersLayer
return { Runtime = runtime; Orders = orders }
}
FsLiveDocsGeneratedPage16_4556FC416C2B.AppEnvRuntime: BaseRuntimeAxial.PlatformService.BaseRuntimeGroups the standard operational services commonly used by workflow hosts.
Orders: IOrderRepoFsLiveDocsGeneratedPage16_4556FC416C2B.IOrderRepoordersLayer: Layer<unit,OrderError,IOrderRepo>Axial.Layers.Layer`3Represents a provisioning step that builds an explicit environment inside a scope. The input environment required to build the layer. The typed failure produced during provisioning. The environment or service bundle produced by the layer.
unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
FsLiveDocsGeneratedPage16_4556FC416C2B.OrderErrorAxial.Layers.LayerModulesucceed: 'output -> Layer<'input,'error,'output>Creates a layer that succeeds with a fixed output value.
``.ctor``: unit -> MemoryOrdersappLayer: Layer<unit,OrderError,AppEnv>layer: LayerBuilderThe layer { } computation expression for provisioning explicit service environments.
runtime: BaseRuntimeAxial.PlatformService.BaseRuntimeModuleHelpers for constructing the standard explicit service bundle used by workflow hosts.
live: Layer<unit,Never,BaseRuntime>Builds the standard live base runtime as an explicit service bundle.
(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
widenError: Layer<'input,Never,'output> -> Layer<'input,'error,'output>Gives a layer that cannot fail with a typed error any error type. Layer.provide and the layer combinators require one error type. Widen a layer that cannot fail, such as BaseRuntime.live, to combine it with layers or workflows that can. let runtime : Layer<unit, string, int> = Layer.succeed 1 |> Layer.widenError
orders: IOrderRepoLayer.provide builds the environment, runs the workflow in it, and releases whatever the layers acquired:
let saveInApp : Flow<AppEnv, OrderError, unit> = save { Id = 3 } |> Flow.localEnv (fun app -> { Orders = app.Orders })
saveInApp |> Layer.provide appLayer |> Flow.run () |> shouldEqual (Exit.Success())
saveInApp: Flow<AppEnv,OrderError,unit>Axial.Flow`3Represents a cold workflow that reads an environment, returns a typed result, and is executed explicitly through one of its execution members such as ToTask, ToAsync, or RunSynchronously. The type of the environment dependency. The type of the failure value. The type of the success value.
FsLiveDocsGeneratedPage16_4556FC416C2B.AppEnvFsLiveDocsGeneratedPage16_4556FC416C2B.OrderErrorunitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
save: Order -> Flow<'a,OrderError,unit>Id: int(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Axial.FlowlocalEnv: ('outerEnvironment -> 'innerEnvironment) -> Flow<'innerEnvironment,'error,'value> -> Flow<'outerEnvironment,'error,'value>Runs a flow against an environment derived from the outer environment. Use this to embed a smaller workflow inside a larger application environment without changing the smaller workflow's type. The mapping is applied at execution time. This is useful for preserving narrow helper signatures while still running everything from one app boundary. A function that maps the outer environment to the inner environment. The flow to run with the inner environment. A flow that expects the outer environment. let flow = Flow.succeed 1 |> Flow.localEnv (fun outer -> outer)
app: AppEnvOrders: IOrderRepoAxial.Layers.LayerModuleprovide: Layer<'input,'error,'environment> -> Flow<'environment,'error,'value> -> Flow<'input,'error,'value>Builds an environment with a layer, runs a downstream flow, and always closes the layer scope. This is the provisioning boundary. It creates a fresh scope, builds the supplied layer inside that scope, runs the downstream flow with the built environment, and finalizes all acquired resources when the downstream flow completes or fails. The layer that builds the downstream environment. The flow to run with the provided environment. A flow that requires only the input environment of the layer. let program () = let runtimeLayer = Layer.succeed "production" let workflow = Flow.envWith String.length Layer.provide runtimeLayer workflow
appLayer: Layer<unit,OrderError,AppEnv>run: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
shouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
Use layers when construction can fail, when resources need cleanup, or when a host container should be validated once at
startup. Plain let! is sequential and dependent; sibling and! bindings are independent and use Layer.merge.
Tutorials
For concrete starting points, use App Record and Layers.

