Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddOpenApi();
builder.Services.AddControllers();

builder.Services.AddHostedService<ExampleBackgroundService>();
Expand All @@ -16,19 +14,18 @@
return config.IsDevelopment() ? new DevelopmentExampleService() : new ExampleService();
});

var serviceProvider = builder.Services.BuildServiceProvider();

Check warning on line 17 in dotnet-dependency-injection/HowToGetAnInstanceOfIServiceProvider/HowToGetAnInstanceOfIServiceProvider/Program.cs

View workflow job for this annotation

GitHub Actions / Build & test (dotnet-dependency-injection/HowToGetAnInstanceOfIServiceProvider)

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'. (https://aka.ms/AA5k895)

Check warning on line 17 in dotnet-dependency-injection/HowToGetAnInstanceOfIServiceProvider/HowToGetAnInstanceOfIServiceProvider/Program.cs

View workflow job for this annotation

GitHub Actions / Build & test (dotnet-dependency-injection/HowToGetAnInstanceOfIServiceProvider)

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'. (https://aka.ms/AA5k895)
var serviceInstance1 = serviceProvider.GetService<IExampleService>();

var app = builder.Build();

var serviceScope = app.Services.CreateScope();
using var serviceScope = app.Services.CreateScope();
var serviceInstance2 = serviceScope.ServiceProvider.GetRequiredService<IExampleService>();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.MapOpenApi();
}

app.UseHttpsRedirection();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"launchUrl": "openapi/v1.json",
"applicationUrl": "https://localhost:7006",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
namespace HowToGetAnInstanceOfIServiceProvider.Services;

public class ExampleBackgroundService(IServiceProvider ServiceProvider) : BackgroundService
public class ExampleBackgroundService(IServiceProvider serviceProvider) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = ServiceProvider.CreateScope();
using var scope = serviceProvider.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IExampleService>();

return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>

Expand All @@ -10,12 +10,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
<PackageReference Include="coverlet.collector" Version="10.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ public void GivenProductionEnvironment_WhenServiceIsResolved_ThenShouldReturnExa
Assert.IsType<ExampleService>(exampleService);
}

[Fact]
public void GivenUnregisteredService_WhenResolved_ThenGetServiceReturnsNullAndGetRequiredServiceThrows()
{
// Arrange
var serviceProvider = new ServiceCollection().BuildServiceProvider();

// Act
var service = serviceProvider.GetService<IExampleService>();
var exception = Record.Exception(() => serviceProvider.GetRequiredService<IExampleService>());

// Assert
Assert.Null(service);
Assert.IsType<InvalidOperationException>(exception);
}

[Fact]
public async Task GivenBackgroundService_WhenStartAsyncIsCalled_ThenShouldNotThrowException()
{
Expand Down
Loading