Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document Interface Composition Working Example #1691

Open
cmeyertons opened this issue Apr 26, 2024 · 0 comments
Open

Document Interface Composition Working Example #1691

cmeyertons opened this issue Apr 26, 2024 · 0 comments

Comments

@cmeyertons
Copy link

I'd like to re-visit the solutioning / documentation around interface composition on latest .NET 8 and Refit.HttpClientFactory 7.

Related to: #49

It appears interface composition now is possible, but is undocumented. I think this would help a population of folks that have larger API surfaces they are trying to create / maintain with Refit.

Interface Composition provides a better UX as you can dive into sub-concerns and not have a globally inherited interface where intellisense, etc is returning everything all the time.

Describe the solution you'd like

Document Refit interface composition.

Describe alternatives you've considered

n/a, it now works (at least with HttpClientFactory)

Describe suggestions on how to achieve the feature

Please see my below code example:

public interface IMainApi
{
    IUsersApi Users { get; }
    IApplicationsApi Applications { get; }
    // could have many more
}

public interface IUsersApi
{
    [Get("/users")]
    Task<object> GetUsers();
}

public interface IApplicationsApi
{
    [Get("/applications")]
    Task<object> GetApplications();
}

internal record MainApi(IUsersApi Users, IApplicationsApi Applications) : IMainApi;

public static class DISetup
{
    private static readonly RefitSettings _settings = new()
    {
        // don't set the primary handler or anything like that that refit would invoke multiple times
    };

    public static IHttpClientBuilder AddMainApiClient(this IServiceCollection services, Uri baseAddress)
    {
        services.AddSingleton<IMainApi, MainApi>();

        var mainBuilder = services.AddRefitClient<IUsersApi>((services) => _settings, nameof(IMainApi));

        //using the same name here causes the underlying http client to be shared
        services.AddRefitClient<IApplicationsApi>((services) => _settings, nameof(IMainApi));

        mainBuilder.ConfigureHttpClient(client => {
            client.BaseAddress = baseAddress;
        });

        return mainBuilder;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant