CA2000 Does not warn on IDisposable instances returned by interface method.
- Dominant language
- C#
- Stars
- 3.2k
- Forks
- 1.3k
- PR merge metrics
- PR metrics pending
Description
**Version Used**: 9.0.307
Today we debugged and found yet another place, where we missed to prepend `using` on caller-owned instances returned by an interface method. More specifically, `dbContext.Database.BeginTransaction(...)`.
Since we have been very strict when it comes to static code analysis settings (`AnalysisMode: All`), we wondered why CA2000 was not raised in this case.
After tested and explored a bit, we found this [open issue 29631](https://github.com/dotnet/runtime/issues/29631), which explains the underlying problem that we are seeing.
We are still creating this issue to highlight the impact of not being able to annotate ownership:
1. Dependency injection patterns heavily rely on interface abstractions.
2. Common APIs like `IDbContextTransaction` from EF Core are accessed through interfaces.
3. Teams relying on static code analyzer have a false sense of security.
**Steps to Reproduce**:
```cs
using System;
using Microsoft.Extensions.DependencyInjection;
public interface IFactory
{
MyDisposableClass CreateInstance();
}
public class MyFactory : IFactory
{
public MyDisposableClass CreateInstance() => new();
}
public sealed class MyDisposableClass : IDisposable
{
public void Dispose()
{
// TODO release managed resources here
}
}
public static class Program
{
public static void Main()
{
// CA2000 Raises
var regularCreate = new MyDisposableClass();
// CA2000 Raises
var closureFactory = () => new MyDisposableClass();
var closureCreate = closureFactory();
// CA2000 Raises
IServiceProvider serviceProvider = null!;
var activatorCreate = ActivatorUtilities.CreateInstance(serviceProvider);
// CA2000 Does Not Raise
IFactory factory = null!;
var factoryCreate = factory.CreateInstance();
// CA2000 Raises
MyFactory myFactory = new();
var myFactoryCreate = myFactory.CreateInstance();
}
}
```
**Diagnostic Id**: CA2000
**Expected Behavior**:
The warning CA2000 raises on `factoryCreate` statement.
**Actual Behavior**:
The warning CA2000 does not raise.
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the provided CA2000 reproduction and compare diagnostics for the concrete and interface-typed factory calls. Investigate the analyzer behavior around IDisposable instances returned through interface methods; done means CA2000 is reported for factoryCreate without regressing the other cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100