Skip to content

Add default PostHog SDK client facade#190

Merged
marandaneto merged 12 commits into
mainfrom
feat/add-default-posthog-sdk-client
May 7, 2026
Merged

Add default PostHog SDK client facade#190
marandaneto merged 12 commits into
mainfrom
feat/add-default-posthog-sdk-client

Conversation

@marandaneto

Copy link
Copy Markdown
Member

💡 Motivation and Context

Adds an optional process-wide default PostHog client facade for console apps, scripts, and other places where passing an IPostHogClient instance around is inconvenient.

💚 How did you test it?

  • dotnet build src/PostHog/PostHog.csproj --no-restore -v:minimal
  • dotnet test tests/UnitTests/UnitTests.csproj --framework net8.0 --no-restore --filter PostHogSdkTests -v:minimal

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Added the release label to the PR
  • Added exactly one version bump label: bump-patch, bump-minor, or bump-major

@github-actions

github-actions Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

posthog-dotnet Compliance Report

Date: 2026-05-07 11:11:41 UTC
Duration: 446ms

⚠️ Some Tests Failed

2/16 tests passed, 14 failed


Feature_Flags Tests

⚠️ 2/16 tests passed, 14 failed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 34ms
Request Payload.Flags Request Uses V2 Query Param 17ms
Request Payload.Flags Request Hits Flags Path Not Decide 4ms
Request Payload.Flags Request Omits Authorization Header 4ms
Request Payload.Token In Flags Body Matches Init 3ms
Request Payload.Groups Round Trip 4ms
Request Payload.Groups Default To Empty Object 4ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 3ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 4ms
Request Payload.Disable Geoip Omitted Defaults To False 4ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 4ms
Request Lifecycle.No Flags Request On Init Alone 2ms
Request Lifecycle.No Flags Request On Normal Capture 167ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 5ms
Request Lifecycle.Mock Response Value Is Returned To Caller 4ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 3ms

Failures

request_payload.request_with_person_properties_device_id

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_uses_v2_query_param

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_hits_flags_path_not_decide

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_omits_authorization_header

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.token_in_flags_body_matches_init

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.groups_round_trip

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.groups_default_to_empty_object

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.person_properties_distinct_id_auto_populated_when_caller_omits_it

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.disable_geoip_false_propagates_as_geoip_disable_false

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.disable_geoip_omitted_defaults_to_false

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flag_keys_to_evaluate_contains_only_requested_key

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_lifecycle.two_flag_calls_produce_two_remote_requests

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_lifecycle.mock_response_value_is_returned_to_caller

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

side_effect_events.get_feature_flag_captures_feature_flag_called_event

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

@marandaneto

Copy link
Copy Markdown
Member Author

@haacked wdyt? i noticed some SDKs don't have a global facade, and you have to pass it around, and sometimes passing it around is tricky, you have to change a lot of method and ctor signatures, and make your code even more coupled to PostHog

@haacked

haacked commented May 1, 2026

Copy link
Copy Markdown
Contributor

@haacked wdyt? i noticed some SDKs don't have a global facade, and you have to pass it around, and sometimes passing it around is tricky, you have to change a lot of method and ctor signatures, and make your code even more coupled to PostHog

I'm not sure this is needed, but I'm not totally opposed to it.

For context, this repo has two packages:

  • PostHog - Core package
  • PostHog.AspNetCore - for web apps

Dependency Injection (aka DI) is very popular in the .NET community. So many developers would be familiar with the approach this library takes which is:

  1. Wire up the client dependencies
  2. Inject the client where its needed.

In particular, this is because certain environments (such as AspNetCore) have specific requirements on how the client is configured. Using a global facade in AspNetCore would almost certainly be wired up wrong.

Our docs explain how to do it: https://posthog.com/docs/libraries/dotnet

using PostHog;

var builder = WebApplication.CreateBuilder(args);

// Add PostHog to the dependency injection container as a singleton.
builder.AddPostHog();

And then inject the client anywhere you needed it.

There may be scenarios where a global Facade makes sense, but I'd rather create a package for that specific scenario. For example, if we wanted to support Maui client apps, we could create a PostHog.Maui package that has a Maui specific DI registration methods and maybe a Maui specific global facade.

@marandaneto

marandaneto commented May 4, 2026

Copy link
Copy Markdown
Member Author

There may be scenarios where a global Facade makes sense, but I'd rather create a package for that specific scenario. For example, if we wanted to support Maui client apps, we could create a PostHog.A Maui package that has Maui-specific DI registration methods and maybe a Maui-specific global facade.

This is not about Maui, as the PR desc says:

console apps, scripts, and other places where passing an IPostHogClient instance around is inconvenient.

I'd agree with a Maui package for sure, but for console apps, scripts, etc., then it's not scalable and maintainable having way too many packages just for setting up a conventional DI where a global facade would do, some other SDKs do this already btw

@marandaneto
marandaneto marked this pull request as ready for review May 4, 2026 08:32
@marandaneto
marandaneto requested review from a team and haacked as code owners May 4, 2026 08:32
@greptile-apps

greptile-apps Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
src/PostHog/PostHogSdk.cs:248-258
**`ShutdownAsync` triggers spurious warning when no client is configured**

When `_defaultClient` is `null`, `Interlocked.Exchange(ref _defaultClient, null)` returns `null`, so `?? Current` is evaluated. `Current` then calls `NoOpPostHogClient.LogNoDefaultClient()`, emitting the "PostHogSdk.DefaultClient is not configured" warning. This contradicts the XML doc which promises the method shuts down "if one is configured." The `Dispose()` teardown in the test suite also hits this path for every test that doesn't set a client.

The fix is to take the client atomically and return early when nothing was configured:

```csharp
public static async ValueTask ShutdownAsync()
{
    var client = Interlocked.Exchange(ref _defaultClient, null);
    if (client is null)
    {
        return;
    }
    try
    {
        await client.FlushAsync();
    }
    finally
    {
        await client.DisposeAsync();
    }
}
```

```suggestion
    public static async ValueTask ShutdownAsync()
    {
        var client = Interlocked.Exchange(ref _defaultClient, null);
        if (client is null)
        {
            return;
        }
```

### Issue 2 of 3
src/PostHog/README.md:38-39
**README example flushes twice**

`ShutdownAsync` internally calls `FlushAsync` before disposing the client, so calling `FlushAsync` just before `ShutdownAsync` in the example results in two sequential flushes. The standalone `FlushAsync` call is redundant and may confuse readers into thinking both calls are always necessary. Consider replacing both lines with just `await PostHogSdk.ShutdownAsync();`.

```suggestion
await PostHogSdk.ShutdownAsync();
```

### Issue 3 of 3
tests/UnitTests/PostHogSdkTests.cs:57-66
**Prefer parameterised tests for the no-op assertions**

`AsyncCallsAreNoOpWithoutDefaultClient` exercises three independent methods in a single `[Fact]`, meaning a failure in the first assertion can silently mask the others. The project's coding standard prefers `[Theory]` / `[InlineData]` parameterised tests for this kind of repetitive-assertion pattern; splitting these into a `[Theory]` would also make the test name self-documenting for each case.

Reviews (1): Last reviewed commit: "Merge branch 'main' into feat/add-defaul..." | Re-trigger Greptile

Comment thread src/PostHog/PostHogSdk.cs
Comment thread src/PostHog/README.md
Comment thread tests/UnitTests/PostHogSdkTests.cs
@marandaneto
marandaneto requested a review from dustinbyrne May 5, 2026 15:17
@haacked

haacked commented May 5, 2026

Copy link
Copy Markdown
Contributor

but for console apps, scripts, etc., then it's not scalable and maintainable having way too many packages just for setting up a conventional DI where a global facade would do, some other SDKs do this already btw

Fair point on Maui not being the analogue. Console/scripts is its own thing. Two concerns I want to separate:

Namespace collision. PostHogSdk and Registration.AddPostHog both live in namespace PostHog. Anyone using PostHog.AspNetCore writes using PostHog; and gets both in IntelliSense. Nothing connects them. AddPostHog doesn't set PostHogSdk.DefaultClient, and the DI singleton is invisible to the facade. So a dev who wires up DI correctly and then calls PostHogSdk.Capture(…) from somewhere DI is awkward (background IHostedService, static helper, test) silently hits NoOpPostHogClient and drops events. The Trace.TraceWarning won't help because most apps don't listen to Trace.

Options:

  1. Move the facade to PostHog.Sdk so it doesn't surface alongside AddPostHog.
  2. Have AddPostHog set DefaultClient to the resolved singleton (and clear on shutdown), or fail fast if DefaultClient is already set. One mental model, not two.
  3. Log via ILogger/EventSource instead of Trace. Throw in DEBUG.

Separate PostHog.Console package. Agreed that one class plus a no-op isn't worth a nupkg. The question is whether we add enough console-specific value to justify one:

  • An Init overload that wires up Microsoft.Extensions.Logging.Console.
  • AppDomain.ProcessExit / Console.CancelKeyPress hooks for auto-flush on Ctrl+C. Scripts lose events all the time because of this.
  • PostHogSdk.RunAsync(options, async client => …) so people don't forget await ShutdownAsync().

With those, the package earns its keep. Without them, agreed it's overkill.

Either way, the namespace collision is my blocker. Can we sort that out first?

@marandaneto

Copy link
Copy Markdown
Member Author

Either way, the namespace collision is my blocker. Can we sort that out first?

sure

@marandaneto

Copy link
Copy Markdown
Member Author

@haacked done

@marandaneto
marandaneto merged commit db7fe08 into main May 7, 2026
14 checks passed
@marandaneto
marandaneto deleted the feat/add-default-posthog-sdk-client branch May 7, 2026 11:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants