microsoft / microsoft/aspire

[Testing] Add a possibility to inject / override services (especially auth) in the projects which are launched from the apphost

Open
#13,656 6 comments 3 reactions 0 assignees View on GitHub
area-app-testing
Dominant language
C#
Stars
6.3k
Forks
991
Avg merge
2d 15h
Merged PRs (30d)
196

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

Hi,
I'm migrating my tests from a manual orchestrated WebapplicationFactory and TestContainers to Aspire. As I used the webappliationfactory - I could create a class like this and manipulate the services within my api-project.
I don't want to ship any test code to production, this worked well with the "classic" WebApplicationFactory and I was able to replace my authprovider with a faked one.

```csharp
public class ApiWebApplicationFactory : WebApplicationFactory
{

protected override void ConfigureWebHost(IWebHostBuilder builder)
{

builder.ConfigureServices(services =>
{
//manipulate some services
var workerService = services.Single(
d => d.ImplementationType == typeof(WorkerService));
services.Remove(workerService);

// add a fake auth provider
services.AddAuthentication(FakeJwtBearerDefaults.AuthenticationScheme).AddFakeJwtBearer();

services.AddAuthorizationBuilder()
.AddPolicy("somename", policy =>
policy
.AddAuthenticationSchemes(FakeJwtBearerDefaults.AuthenticationScheme)
.RequireRole("client_role"));

});

}

}
```

### Describe the solution you'd like

Add a simple way to manipulate the services in a related project so that I can fake my authprovider without shipping testcode into production later.
Maybe like this:
```csharp
var appHost = await DistributedApplicationTestingBuilder.CreateAsync();
//Where "apiService" is the name of the project in the apphost
appHost.ConfigureServices("apiService", services =>{
// add a fake auth provider
services.AddAuthentication(FakeJwtBearerDefaults.AuthenticationScheme).AddFakeJwtBearer();

services.AddAuthorizationBuilder()
.AddPolicy("somename", policy =>
policy
.AddAuthenticationSchemes(FakeJwtBearerDefaults.AuthenticationScheme)
.RequireRole("client_role"));

// and maybe change some services as well
var workerService = services.Single(
d => d.ImplementationType == typeof(WorkerService));
services.Remove(workerService);
});
await using var app = await appHost.BuildAsync();
```

### Additional context

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.