dotnet / dotnet/aspnetcore

Sometimes service marked with [FromServices] attribute isn't injected into controller's action

Open
#48,671 12 comments 6 reactions 0 assignees View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

We have controller's action like this:

```csharp
public async Task> Upload(
[FromQuery] string sid,
[FromQuery] string uniqueKey,
[FromQuery] string fileName,
[FromServices] ISftpClientFactory sftpClientFactory,
[FromServices] ITempFileStreamFactory tempFileStreamFactory)
{
if (sftpClientFactory == null) throw new ArgumentNullException(nameof(sftpClientFactory));
if (tempFileStreamFactory == null) throw new ArgumentNullException(nameof(tempFileStreamFactory));

// some logic goes here
}
```
We injects `ISftpClientFactory` and `ITempFileStreamFactory` instances as dependencies. They marked with `[FromServices]`. All services are registered.

99.99% of all request processed correctly. But sometimes we get null instead of this services. And null checks throws an exception:
```
System.ArgumentNullException: Value cannot be null. (Parameter 'sftpClientFactory')
```

We doesn't change request's pipeline dynamically. Here is our configured pipeline:
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (app == null) throw new ArgumentNullException(nameof(app));
if (env == null) throw new ArgumentNullException(nameof(env));

app.UseRouting();
app.UseMiddleware();

app.UseReverseProxy(Configuration.ReverseProxy);

app.UseCors("CorsPolicy");

app.UseMiddleware();

if (Configuration.LogRequestContent)
app.UseMiddleware();

var localizationOptions = app.ApplicationServices.GetService>();
app.UseRequestLocalization(localizationOptions.Value);

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "DefaultApi",
pattern: "{version}/{controller}/{action}",
constraints: new { version = "v4|v5|v6" });
});
}
```
All of this middleware doesn't change pipeline's flow.

Here is example of registration of those services:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton();
services.TryAddSingleton();

// other services registration...
}
```

### Expected Behaviour

Dependencies are always not null

### Steps To Reproduce

No specific steps, the error occurs randomly.

### Exceptions (if any)

```csharp
System.ArgumentNullException: Value cannot be null. (Parameter 'sftpClientFactory')
at SIISLtd.SSNG.WebAPI.Controllers.FileController.Upload(String sid, String uniqueKey, String fileName, ISftpClientFactory sftpClientFactory, ITempFileStreamFactory tempFileStreamFactory) in /home/xpg934/ssng/src/Web/SIISLtd.SSNG.WebAPI/Controllers/FileController.cs:line 110
at lambda_method2228(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at SIISLtd.SSNG.WebTools.Middleware.RequestLoggingMiddleware.InvokeAsync(HttpContext context) in /home/xpg934/ssng/src/Web/SIISLtd.SSNG.WebTools/Middleware/RequestLoggingMiddleware.cs:line 70
at SIISLtd.SSNG.WebTools.Middleware.PerformanceMeasureMiddleware.InvokeAsync(HttpContext context) in /home/xpg934/ssng/src/Web/SIISLtd.SSNG.WebTools/Middleware/PerformanceMeasureMiddleware.cs:line 48
at SIISLtd.SSNG.WebAPI.Middleware.ApiGlobalExceptionHandleMiddleware.InvokeAsync(HttpContext httpContext) in /home/xpg934/ssng/src/Web/SIISLtd.SSNG.WebAPI/Middleware/ApiGlobalExceptionHandleMiddleware.cs:line 32
```

### .NET Version

6.0.0

### Anything else?

Host (useful for support):
Version: 6.0.0
Commit: 4822e3c3aa

.NET SDKs installed:
No SDKs were found.

.NET runtimes installed:
Microsoft.AspNetCore.All 2.2.8 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.2.8 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.12 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 6.0.0 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.2.8 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.12 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Microsoft.NETCore.App 6.0.0 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET runtimes or SDKs:
https://aka.ms/dotnet-download

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.