DI012

Conditional Registration Misuse

- TryAdd* calls after an Add* already registered that service.

Info Default severity · Code fix: Yes

Why it matters

Registration intent becomes unclear and behaviour differs from what readers expect.

Writing your name on the same seat twice does not get you two seats; one note just replaces the other.

README problem example

services.AddSingleton<IMyService, ServiceA>();
services.TryAddSingleton<IMyService, ServiceB>(); // ignored

services.AddSingleton<IMyService, ServiceA>();
services.AddSingleton<IMyService, ServiceB>(); // overrides A

Code fix

Yes for ignored TryAdd* and TryAddKeyed* calls that are block-contained standalone statements; the fixer removes the redundant ignored registration. Duplicate override cases and embedded single-line statement bodies remain manual.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

Sample app warning case

        // ⚠️ BAD: TryAdd will be ignored because ServiceA is already registered
        services.AddSingleton<IService, ServiceA>();
        services.TryAddSingleton<IService, ServiceB>(); // Diagnostic here

        // ⚠️ BAD: Multiple Add calls (Duplicate Registration)
        // The second registration overrides the first for single resolution
        services.AddScoped<ServiceA>();
        services.AddScoped<ServiceA>(); // Diagnostic here
    }
}

Sample app duplicate-registration case

        // ⚠️ BAD: Multiple Add calls (Duplicate Registration)
        // The second registration overrides the first for single resolution
        services.AddScoped<ServiceA>();
        services.AddScoped<ServiceA>(); // Diagnostic here
    }
}

Nearby diagnostics

Other rules in this family

All 37 rules