{"id":25272055,"url":"https://github.com/audunhalland/entrait","last_synced_at":"2025-04-12T18:46:34.490Z","repository":{"id":39745722,"uuid":"462709782","full_name":"audunhalland/entrait","owner":"audunhalland","description":"Loosely coupled Rust application design made easy","archived":false,"fork":false,"pushed_at":"2025-01-09T12:14:39.000Z","size":466,"stargazers_count":95,"open_issues_count":3,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-03T22:07:13.355Z","etag":null,"topics":["domain-driven-development","inversion-of-control","loose-coupling","rust","testing"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/audunhalland.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-02-23T11:40:44.000Z","updated_at":"2025-03-18T14:48:36.000Z","dependencies_parsed_at":"2024-03-25T01:26:13.225Z","dependency_job_id":"c8480ffb-7eb4-40b8-9f10-66bee4df49f5","html_url":"https://github.com/audunhalland/entrait","commit_stats":{"total_commits":346,"total_committers":1,"mean_commits":346.0,"dds":0.0,"last_synced_commit":"fd6919631bbe98640a7b46dce43a9bc10187b05a"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Fentrait","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Fentrait/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Fentrait/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audunhalland%2Fentrait/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/audunhalland","download_url":"https://codeload.github.com/audunhalland/entrait/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248617582,"owners_count":21134195,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["domain-driven-development","inversion-of-control","loose-coupling","rust","testing"],"created_at":"2025-02-12T12:39:15.191Z","updated_at":"2025-04-12T18:46:34.468Z","avatar_url":"https://github.com/audunhalland.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# entrait\n\n[\u003cimg alt=\"crates.io\" src=\"https://img.shields.io/crates/v/entrait.svg?style=for-the-badge\u0026logo=rust\" height=\"20\"\u003e](https://crates.io/crates/entrait)\n[\u003cimg alt=\"docs.rs\" src=\"https://img.shields.io/docsrs/entrait?style=for-the-badge\u0026logo=docs.rs\" height=\"20\"\u003e](https://docs.rs/entrait)\n[\u003cimg alt=\"CI\" src=\"https://img.shields.io/github/actions/workflow/status/audunhalland/entrait/rust.yml?branch=main\u0026style=for-the-badge\u0026logo=github\" height=\"20\"\u003e](https://github.com/audunhalland/entrait/actions?query=branch%3Amain)\n[\u003cimg alt=\"Discord\" src=\"https://img.shields.io/discord/1233771789348507698?style=for-the-badge\u0026logo=discord\" height=\"20\"\u003e](https://discord.gg/nw9ZWP9kvy)\n\n\u003c!-- cargo-rdme start --\u003e\n\nA proc macro for designing loosely coupled Rust applications.\n\n[`entrait`](entrait) is used to generate an _implemented trait_ from the definition of regular functions.\nThe emergent pattern that results from its use enable the following things:\n* Zero-cost loose coupling and inversion of control\n* Dependency graph as a compile time concept\n* Mock library integrations\n* Clean, readable, boilerplate-free code\n\nThe resulting pattern is referred to as [the entrait pattern](https://audunhalland.github.io/blog/entrait-pattern/) (see also: [philosophy](#philosophy)).\n\n## Introduction\n\nThe macro looks like this:\n\n```rust\n#[entrait(MyFunction)]\nfn my_function\u003cD\u003e(deps: \u0026D) {\n}\n```\n\nwhich generates a new single-method trait named `MyFunction`, with the method signature derived from the original function.\nEntrait is a pure append-only macro: It will never alter the syntax of your function.\nThe new language items it generates will appear below the function.\n\nIn the first example, `my_function` has a single parameter called `deps` which is generic over a type `D`, and represents dependencies injected into the function.\nThe dependency parameter is always the first parameter, which is analogous to the `\u0026self` parameter of the generated trait method.\n\nTo add a dependency, we just introduce a trait bound, now expressable as `impl Trait`.\nThis is demonstrated by looking at one function calling another:\n\n```rust\n#[entrait(Foo)]\nfn foo(deps: \u0026impl Bar) {\n    println!(\"{}\", deps.bar(42));\n}\n\n#[entrait(Bar)]\nfn bar\u003cD\u003e(deps: \u0026D, n: i32) -\u003e String {\n    format!(\"You passed {n}\")\n}\n```\n\n\n#### Multiple dependencies\nOther frameworks might represent multiple dependencies by having one value for each one, but entrait represents all dependencies _within the same value_.\nWhen the dependency parameter is generic, its trait bounds specifiy what methods we expect to be callable inside the function.\n\nMultiple bounds can be expressed using the `\u0026(impl A + B)` syntax.\n\nThe single-value dependency design means that it is always the same reference that is passed around everywhere.\nBut a reference to what, exactly?\nThis is what we have managed to abstract away, which is the [whole point](#testing).\n\n\n\n#### Runtime and implementation\nWhen we want to compile a working application, we need an actual type to inject into the various entrait entrypoints.\nTwo things will be important:\n\n* All trait bounds used deeper in the graph will implicitly \"bubble up\" to the entrypoint level, so the type we eventually use will need to implement all those traits in order to type check.\n* The implementations of these traits need to do the correct thing: Actually call the entraited function, so that the dependency graph is turned into an actual _call graph_.\n\nEntrait generates _implemented traits_, and the type to use for linking it all together is `Impl\u003cT\u003e`:\n\n```rust\n#[entrait(Foo)]\nfn foo(deps: \u0026impl Bar) -\u003e i32 {\n    deps.bar()\n}\n\n#[entrait(Bar)]\nfn bar(_deps: \u0026impl std::any::Any) -\u003e i32 {\n    42\n}\n\nlet app = Impl::new(());\nassert_eq!(42, app.foo());\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\nThe linking happens in the generated impl block for `Impl\u003cT\u003e`, putting the entire impl under a where clause derived from the original dependency bounds:\n\n```rust\nimpl\u003cT: Sync\u003e Foo for Impl\u003cT\u003e where Self: Bar {\n    fn foo(\u0026self) -\u003e i32 {\n        foo(self) // \u003c---- calls your function\n    }\n}\n```\n\u003c/details\u003e\n\n`Impl` is generic, so we can put whatever type we want into it.\nNormally this would be some type that represents the global state/configuration of the running application.\nBut if dependencies can only be traits, and we always abstract away this type, how can this state ever be accessed?\n\n\n\n#### Concrete dependencies\nSo far we have only seen generic trait-based dependencies, but the dependency can also be a _concrete type_:\n\n```rust\nstruct Config(i32);\n\n#[entrait(UseTheConfig)]\nfn use_the_config(config: \u0026Config) -\u003e i32 {\n    config.0\n}\n\n#[entrait(DoubleIt)]\nfn double_it(deps: \u0026impl UseTheConfig) -\u003e i32 {\n    deps.use_the_config() * 2\n}\n\nassert_eq!(42, Impl::new(Config(21)).double_it());\n```\n\nThe parameter of `use_the_config` is in the first position, so it represents the dependency.\n\nWe will notice two interesting things:\n* Functions that depend on `UseTheConfig`, either directly or indirectly, now have only one valid dependency type: `Impl\u003cConfig\u003e`\u003csup\u003e[1](#case-1-concrete-leaf-dependencies)\u003c/sup\u003e.\n* Inside `use_the_config`, we have a `\u0026Config` reference instead of `\u0026Impl\u003cConfig\u003e`. This means we cannot call other entraited functions, because they are not implemented for `Config`.\n\nThe last point means that a concrete dependency is the end of the line, a leaf in the dependency graph.\n\nTypically, functions with a concrete dependency should be kept small and avoid extensive business logic.\nThey ideally function as accessors, providing a loosely coupled abstraction layer over concrete application state.\n\n\n#### Module support\nTo reduce the number of generated traits, entrait can be used as a `mod` attribute.\nWhen used in this mode, the macro will look for non-private functions directly within the module scope, to be represented as methods on the resulting trait.\nThis mode works mostly identically to the standalone function mode.\n\n```rust\n#[entrait(pub MyModule)]\nmod my_module {\n    pub fn foo(deps: \u0026impl super::SomeTrait) {}\n    pub fn bar(deps: \u0026impl super::OtherTrait) {}\n}\n```\nThis example generates a `MyModule` trait containing the methods `foo` and `bar`.\n\n\n## Testing\n### Trait mocking with `Unimock`\n\nThe whole point of entrait is to provide inversion of control, so that alternative dependency implementations can be used when unit testing function bodies.\nWhile test code can contain manual trait implementations, the most ergonomic way to test is to use a mocking library, which provides more features with less code.\n\nEntrait works best together with [unimock](https://docs.rs/unimock/latest/unimock/), as these two crates have been designed from the start with each other in mind.\n\nUnimock exports a single mock struct which can be passed as argument to every function that accept a generic `deps` parameter\n  (given that entrait is used with unimock support everywhere).\nTo enable mock configuration of entraited functions, supply the `mock_api` option, e.g. `mock_api=TraitMock` if the name of the trait is `Trait`.\nThis works the same way for entraited modules, only that those already _have_ a module to export from.\n\nUnimock support for entrait is enabled by passing the `unimock` option to entrait (`#[entrait(Foo, unimock)]`), or turning on the `unimock` _feature_, which makes all entraited functions mockable, even in upstream crates (as long as `mock_api` is provided.).\n\n```rust\n#[entrait(Foo, mock_api=FooMock)]\nfn foo\u003cD\u003e(_: \u0026D) -\u003e i32 {\n    unimplemented!()\n}\n#[entrait(MyMod, mock_api=mock)]\nmod my_mod {\n    pub fn bar\u003cD\u003e(_: \u0026D) -\u003e i32 {\n        unimplemented!()\n    }\n}\n\nfn my_func(deps: \u0026(impl Foo + MyMod)) -\u003e i32 {\n    deps.foo() + deps.bar()\n}\n\nlet mocked_deps = Unimock::new((\n    FooMock.each_call(matching!()).returns(40),\n    my_mod::mock::bar.each_call(matching!()).returns(2),\n));\n\nassert_eq!(42, my_func(\u0026mocked_deps));\n```\n\n##### Deep integration testing with unimock\nEntrait with unimock supports _un-mocking_. This means that the test environment can be _partially mocked!_\n\n```rust\n#[entrait(SayHello)]\nfn say_hello(deps: \u0026impl FetchPlanetName, planet_id: u32) -\u003e Result\u003cString, ()\u003e {\n    Ok(format!(\"Hello {}!\", deps.fetch_planet_name(planet_id)?))\n}\n\n#[entrait(FetchPlanetName)]\nfn fetch_planet_name(deps: \u0026impl FetchPlanet, planet_id: u32) -\u003e Result\u003cString, ()\u003e {\n    let planet = deps.fetch_planet(planet_id)?;\n    Ok(planet.name)\n}\n\npub struct Planet {\n    name: String\n}\n\n#[entrait(FetchPlanet, mock_api=FetchPlanetMock)]\nfn fetch_planet(deps: \u0026(), planet_id: u32) -\u003e Result\u003cPlanet, ()\u003e {\n    unimplemented!(\"This doc test has no access to a database :(\")\n}\n\nlet hello_string = say_hello(\n    \u0026Unimock::new_partial(\n        FetchPlanetMock\n            .some_call(matching!(123456))\n            .returns(Ok(Planet {\n                name: \"World\".to_string(),\n            }))\n    ),\n    123456,\n).unwrap();\n\nassert_eq!(\"Hello World!\", hello_string);\n```\n\nThis example used [`Unimock::new_partial`](unimock::Unimock::new_partial) to create a mocker that works mostly like `Impl`, except that the call graph can be short-circuited at arbitrary, run-time configurable points.\nThe example code goes through three layers (`say_hello =\u003e fetch_planet_name =\u003e fetch_planet`), and only the deepest one gets mocked out.\n\n\n#### Alternative mocking: Mockall\nIf you instead wish to use a more established mocking crate, there is also support for [mockall](https://docs.rs/mockall/latest/mockall/).\nNote that mockall has some limitations.\nMultiple trait bounds are not supported, and deep tests will not work.\nAlso, mockall tends to generate a lot of code, often an order of magnitude more than unimock.\n\nEnabling mockall is done using the `mockall` entrait option.\nThere is no cargo feature to turn this on implicitly, because mockall doesn't work well when it's re-exported through another crate.\n\n```rust\n#[entrait(Foo, mockall)]\nfn foo\u003cD\u003e(_: \u0026D) -\u003e u32 {\n    unimplemented!()\n}\n\nfn my_func(deps: \u0026impl Foo) -\u003e u32 {\n    deps.foo()\n}\n\nfn main() {\n    let mut deps = MockFoo::new();\n    deps.expect_foo().returning(|| 42);\n    assert_eq!(42, my_func(\u0026deps));\n}\n```\n\n\n## Multi-crate architecture\n\nA common technique for Rust application development is to choose a multi-crate architecture.\nThere are usually two main ways to go about it:\n\n1. The call graph and crate dependency go in the same direction.\n2. The call graph and crate dependency go in _opposite_ directions.\n\nThe first option is how libraries are normally used: Its functions are just called, without any indirection.\n\nThe second option can be referred to as a variant of the\n    [dependency inversion principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle).\nThis is usually a desirable architectural property, and achieving this with entrait is what this section is about.\n\nThe main goal is to be able to express business logic _centrally_, and avoid depending directly on infrastructure details (onion architecture).\nAll of the examples in this section make some use of traits and trait delegation.\n\n\n#### Case 1: Concrete leaf dependencies\nEarlier it was mentioned that when concrete-type dependencies are used, the `T` in `Impl\u003cT\u003e`, your application, and the type of the dependency have to match.\nBut this is only partially true.\nIt really comes down to which traits are implemented on what types:\n\n```rust\npub struct Config {\n    foo: String,\n}\n\n#[entrait_export(pub GetFoo)]\nfn get_foo(config: \u0026Config) -\u003e \u0026str {\n    \u0026config.foo\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\n```rust\ntrait GetFoo {\n    fn get_foo(\u0026self) -\u003e \u0026str;\n}\nimpl\u003cT: GetFoo\u003e GetFoo for Impl\u003cT\u003e {\n    fn get_foo(\u0026self) -\u003e \u0026str {\n        self.as_ref().get_foo()\n    }\n}\nimpl GetFoo for Config {\n    fn get_foo(\u0026self) -\u003e \u0026str {\n        get_foo(self)\n    }\n}\n```\n\n\u003c/details\u003e\n\nHere we actually have a trait `GetFoo` that is implemented two times: for `Impl\u003cT\u003e where T: GetFoo` and for `Config`.\nThe first implementation is delegating to the other one.\n\nFor making this work with _any_ downstream application type, we just have to manually implement `GetFoo` for that application:\n\n```rust\nstruct App {\n    config: some_upstream_crate::Config,\n}\nimpl some_upstream_crate::GetFoo for App {\n    fn get_foo(\u0026self) -\u003e \u0026str {\n        self.config.get_foo()\n    }\n}\n```\n\n\n#### Case 2: Hand-written trait as a leaf dependency\nUsing a concrete type like `Config` from the first case can be contrived in many situations.\nSometimes a good old hand-written trait definition will do the job much better:\n\n```rust\n#[entrait]\npub trait System {\n    fn current_time(\u0026self) -\u003e u128;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\n```rust\nimpl\u003cT: System\u003e System for Impl\u003cT\u003e {\n    fn current_time(\u0026self) -\u003e u128 {\n        self.as_ref().current_time()\n    }\n}\n```\n\n\u003c/details\u003e\n\nWhat the attribute does in this case, is just to generate the correct blanket implementations of the trait: _delegation_ and _mocks_.\n\nTo use with some `App`, the app type itself should implement the trait.\n\n\n#### Case 3: Hand-written trait as a leaf dependency using _dynamic dispatch_\nSometimes it might be desirable to have a delegation that involves dynamic dispatch.\nEntrait has a `delegate_by =` option, where you can pass an alternative trait to use as part of the delegation strategy.\nTo enable dynamic dispatch, use [`ref`](https://doc.rust-lang.org/stable/core/convert/trait.AsRef.html):\n\n```rust\n#[entrait(delegate_by=ref)]\ntrait ReadConfig: 'static {\n    fn read_config(\u0026self) -\u003e \u0026str;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\n```rust\nimpl\u003cT: ::core::convert::AsRef\u003cdyn ReadConfig\u003e + 'static\u003e ReadConfig for Impl\u003cT\u003e {\n    fn read_config(\u0026self) -\u003e \u0026str {\n        self.as_ref().as_ref().read_config()\n    }\n}\n```\n\n\u003c/details\u003e\n\nTo use this together with some `App`, it should implement the [`AsRef\u003cdyn ReadConfig\u003e`](https://doc.rust-lang.org/stable/core/convert/trait.AsRef.html) trait.\n\n\n#### Case 4: Truly inverted _internal dependencies_ - static dispatch\nAll cases up to this point have been _leaf dependencies_.\nLeaf dependencies are delegations that exit from the `Impl\u003cT\u003e` layer, using delegation targets involving concete `T`'s.\nThis means that it is impossible to continue to use the entrait pattern and extend your application behind those abstractions.\n\nTo make your abstraction _extendable_ and your dependency _internal_, we have to keep the `T` generic inside the [Impl] type.\nTo make this work, we have to make use of two helper traits:\n\n```rust\n#[entrait(RepositoryImpl, delegate_by = DelegateRepository)]\npub trait Repository {\n    fn fetch(\u0026self) -\u003e i32;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\n```rust\npub trait RepositoryImpl\u003cT\u003e {\n    fn fetch(_impl: \u0026Impl\u003cT\u003e) -\u003e i32;\n}\npub trait DelegateRepository\u003cT\u003e {\n    type Target: RepositoryImpl\u003cT\u003e;\n}\nimpl\u003cT: DelegateRepository\u003cT\u003e\u003e Repository for Impl\u003cT\u003e {\n    fn fetch(\u0026self) -\u003e i32 {\n        \u003cT as DelegateRepository\u003cT\u003e\u003e::Target::fetch(self)\n    }\n}\n```\n\n\u003c/details\u003e\n\nThis syntax introduces a total of _three_ traits:\n\n* `Repository`: The _dependency_, what the rest of the application directly calls.\n* `RepositoryImpl\u003cT\u003e`: The _delegation target_, a trait which needs to be implemented by some `Target` type.\n* `DelegateRepository\u003cT\u003e`: The _delegation selector_, that selects the specific `Target` type to be used for some specific `App`.\n\nThis design makes it possible to separate concerns into three different crates, ordered from most-upstream to most-downstream:\n1. _Core logic:_ Depend on and call `Repository` methods.\n2. _External system integration:_ Provide some implementation of the repository, by implementing `RepositoryImpl\u003cT\u003e`.\n3. _Executable:_ Construct an `App` that selects a specific repository implementation from crate 2.\n\nAll delegation from `Repository` to `RepositoryImpl\u003cT\u003e` goes via the `DelegateRepository\u003cT\u003e` trait.\nThe method signatures in `RepositoryImpl\u003cT\u003e` are _static_, and receives the `\u0026Impl\u003cT\u003e` via a normal parameter.\nThis allows us to continue using entrait patterns within those implementations!\n\nIn _crate 2_, we have to provide an implementation of `RepositoryImpl\u003cT\u003e`.\nThis can either be done manually, or by using the [entrait] attribute on an `impl` block:\n\n```rust\npub struct MyRepository;\n\n#[entrait]\nimpl crate1::RepositoryImpl for MyRepository {\n    // this function has the now-familiar entrait-compatible signature:\n    fn fetch\u003cD\u003e(deps: \u0026D) -\u003e i32 {\n        unimplemented!()\n    }\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e🔬 \u003cstrong\u003eInspect the generated code\u003c/strong\u003e 🔬\u003c/summary\u003e\n\n```rust\nimpl MyRepository {\n    fn fetch\u003cD\u003e(deps: \u0026D) -\u003e i32 {\n        unimplemented!()\n    }\n}\nimpl\u003cT\u003e crate1::RepositoryImpl\u003cT\u003e for MyRepository {\n    #[inline]\n    fn fetch(_impl: \u0026Impl\u003cT\u003e) -\u003e i32 {\n        Self::fetch(_impl)\n    }\n}\n```\n\n\u003c/details\u003e\n\nEntrait will split this trait implementation block in two: An _inherent_ one containing the original code, and a proper trait implementation which performs the delegation.\n\nIn the end, we just have to implement our `DelegateRepository\u003cT\u003e`:\n\n```rust\n// in crate3:\nstruct App;\nimpl crate1::DelegateRepository\u003cSelf\u003e for App {\n    type Target = crate2::MyRepository;\n}\nfn main() { /* ... */ }\n```\n\n\n#### Case 5: Truly inverted internal dependencies - dynamic dispatch\nA small variation of case 4: Use `delegate_by=ref` instead of a custom trait.\nThis makes the delegation happen using dynamic dispatch.\n\nThe implementation syntax is almost the same as in case 4, only that the entrait attribute must now be `#[entrait(ref)]`:\n\n```rust\n#[entrait(RepositoryImpl, delegate_by=ref)]\npub trait Repository {\n    fn fetch(\u0026self) -\u003e i32;\n}\n\npub struct MyRepository;\n\n#[entrait(ref)]\nimpl RepositoryImpl for MyRepository {\n    fn fetch\u003cD\u003e(deps: \u0026D) -\u003e i32 {\n        unimplemented!()\n    }\n}\n```\n\nThe app must now implement [`AsRef\u003cdyn RepositoryImpl\u003cSelf\u003e\u003e`](https://doc.rust-lang.org/stable/core/convert/trait.AsRef.html).\n\n\n\n\n## Options and features\n\n##### Trait visibility\nby default, entrait generates a trait that is module-private (no visibility keyword).\nTo change this, just put a visibility specifier before the trait name:\n\n```rust\nuse entrait::*;\n#[entrait(pub Foo)]   // \u003c-- public trait\nfn foo\u003cD\u003e(deps: \u0026D) { // \u003c-- private function\n}\n```\n\n##### async support\nZero-cost, static-dispatch `async` works out of the box[^1].\n\nWhen dynamic dispatch is needed, for example in combination with `delegate_by=ref`, entrait understands the `#[async_trait]` attribute when applied _after_ the entrait macro.\nEntrait will re-apply that macro to the various generated impl blocks as needed.\n\n###### async `Send`-ness\nSimilar to `async_trait`, entrait generates a [Send]-bound on futures by default.\nTo opt out of the Send bound, pass `?Send` as a macro argument:\n\n```rust\n#[entrait(ReturnRc, ?Send)]\nasync fn return_rc(_deps: impl Any) -\u003e Rc\u003ci32\u003e {\n    Rc::new(42)\n}\n```\n\n##### Integrating with other `fn`-targeting macros, and `no_deps`\nSome macros are used to transform the body of a function, or generate a body from scratch.\nFor example, we can use [`feignhttp`](https://docs.rs/feignhttp/latest/feignhttp/) to generate an HTTP client. Entrait will try as best as it\ncan to co-exist with macros like these. Since `entrait` is a higher-level macro that does not touch fn bodies (it does not even try to parse them),\nentrait should be processed after, which means it should be placed _before_ lower level macros. Example:\n\n```rust\n#[entrait(FetchThing, no_deps)]\n#[feignhttp::get(\"https://my.api.org/api/{param}\")]\nasync fn fetch_thing(#[path] param: String) -\u003e feignhttp::Result\u003cString\u003e {}\n```\n\nHere we had to use the `no_deps` entrait option.\nThis is used to tell entrait that the function does not have a `deps` parameter as its first input.\nInstead, all the function's inputs get promoted to the generated trait method.\n\n##### Conditional compilation of mocks\nMost often, you will only need to generate mock implementations for test code, and skip this for production code.\nA notable exception to this is when building libraries.\nWhen an application consists of several crates, downstream crates would likely want to mock out functionality from libraries.\n\nEntrait calls this _exporting_, and it unconditionally turns on autogeneration of mock implementations:\n\n```rust\n#[entrait_export(pub Bar)]\nfn bar(deps: \u0026()) {}\n```\nor\n```rust\n#[entrait(pub Foo, export)]\nfn foo(deps: \u0026()) {}\n```\n\nIt is also possible to reduce noise by doing `use entrait::entrait_export as entrait`.\n\n##### Feature overview\n| Feature                  | Implies         | Description         |\n| -------------------      | --------------- | ------------------- |\n| `unimock`                |                 | Adds the [unimock] dependency, and turns on Unimock implementations for all traits. |\n\n\n## \"Philosophy\"\nThe `entrait` crate is central to the _entrait pattern_, an opinionated yet flexible and _Rusty_ way to build testable applications/business logic.\n\nTo understand the entrait model and how to achieve Dependency Injection (DI) with it, we can compare it with a more widely used and classical alternative pattern:\n    _Object-Oriented DI_.\n\nIn object-oriented DI, each named dependency is a separate object instance.\nEach dependency exports a set of public methods, and internally points to a set of private dependencies.\nA working application is built by fully instantiating such an _object graph_ of interconnected dependencies.\n\nEntrait was built to address two drawbacks inherent to this design:\n\n* Representing a _graph_ of objects (even if acyclic) in Rust usually requires reference counting/heap allocation.\n* Each \"dependency\" abstraction often contains a lot of different functionality.\n    As an example, consider [DDD](https://en.wikipedia.org/wiki/Domain-driven_design)-based applications consisting of `DomainServices`.\n    There will typically be one such class per domain object, with a lot of methods in each.\n    This results in dependency graphs with fewer nodes overall, but the number of possible _call graphs_ is much larger.\n    A common problem with this is that the _actual dependencies_—the functions actually getting called—are encapsulated\n        and hidden away from public interfaces.\n    To construct valid dependency mocks in unit tests, a developer will have to read through full function bodies instead of looking at signatures.\n\n`entrait` solves this by:\n\n* Representing dependencies as _traits_ instead of types, automatically profiting from Rust's builtin zero-cost abstraction tool.\n* Giving users a choice between fine and coarse dependency granularity, by enabling both single-function traits and module-based traits.\n* Always declaring dependencies at the function signature level, close to call sites, instead of at module level.\n\n\n## Limitations\nThis section lists known limitations of entrait:\n\n#### Cyclic dependency graphs\nCyclic dependency graphs are impossible with entrait.\nIn fact, this is not a limit of entrait itself, but with Rust's trait solver.\nIt is not able to prove that a type implements a trait if it needs to prove that it does in order to prove it.\n\nWhile this is a limitation, it is not necessarily a bad one.\nOne might say that a layered application architecture should never contain cycles.\nIf you do need recursive algorithms, you could model this as utility functions outside of the entraited APIs of the application.\n\n[^1]: Literally, out of the [Box]! In entrait version 0.7 and newer, asynchronous functions are zero-cost by default.\n\n\u003c!-- cargo-rdme end --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudunhalland%2Fentrait","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faudunhalland%2Fentrait","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudunhalland%2Fentrait/lists"}