惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
雷峰网
雷峰网
IT之家
IT之家
I
InfoQ
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
月光博客
月光博客
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
G
Google Developers Blog
小众软件
小众软件
宝玉的分享
宝玉的分享
Jina AI
Jina AI
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Why Avoid Service Locators in Dependency Injection?
Hossein Esmati · 2026-06-26 · via DEV Community

Hossein Esmati

Why Avoid Service Locators?

Service Locator is an anti-pattern where you inject IServiceProvider and manually resolve dependencies:

// ❌ Bad - Service Locator pattern
public class OrderService
{
    private readonly IServiceProvider _serviceProvider;

    public OrderService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void ProcessOrder()
    {
        var repo = _serviceProvider.GetRequiredService<IOrderRepository>();
        var emailer = _serviceProvider.GetRequiredService<IEmailService>();
        // ...
    }
}

Problems with this approach:

  1. Hidden dependencies - You can't tell what the class needs just by looking at its constructor. Dependencies are obscured inside the implementation.

  2. Runtime failures - Missing dependencies only fail at runtime when that code path executes, not at application startup.

  3. Hard to test - You have to mock IServiceProvider and set up complex mock behaviors instead of just passing in the dependencies.

  4. Breaks IoC principle - The class is now coupled to the DI container itself, defeating the purpose of dependency injection.

Better approach - Constructor Injection:

// ✅ Good - Dependencies are explicit
public class OrderService
{
    private readonly IOrderRepository _repository;
    private readonly IEmailService _emailer;

    public OrderService(IOrderRepository repository, IEmailService emailer)
    {
        _repository = repository;
        _emailer = emailer;
    }

    public void ProcessOrder()
    {
        // Use _repository and _emailer directly
    }
}

Why Isolate Registrations Per Module?

Isolation means organizing your DI registrations by feature/module rather than dumping everything in Program.cs:

// ❌ Bad - Everything in one place
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // 200+ lines of service registrations for all modules...
        builder.Services.AddScoped<IOrderRepository, OrderRepository>();
        builder.Services.AddScoped<IOrderService, OrderService>();
        builder.Services.AddScoped<IProductRepository, ProductRepository>();
        builder.Services.AddScoped<IUserRepository, UserRepository>();
        builder.Services.AddScoped<IAuthService, AuthService>();
        // ... many more
    }
}

Better approach - Extension methods per module:

// ✅ Good - Orders module owns its registrations
public static class OrdersServiceExtensions
{
    public static IServiceCollection AddOrdersModule(this IServiceCollection services)
    {
        services.AddScoped<IOrderRepository, OrderRepository>();
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<IOrderValidator, OrderValidator>();
        return services;
    }
}

// Auth module
public static class AuthServiceExtensions
{
    public static IServiceCollection AddAuthModule(this IServiceCollection services)
    {
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IAuthService, AuthService>();
        return services;
    }
}

// Program.cs stays clean
builder.Services.AddOrdersModule();
builder.Services.AddAuthModule();
builder.Services.AddProductsModule();

Benefits:

  1. Maintainability - Each module's dependencies are colocated with that module's code.

  2. Discoverability - Easy to find what services a module provides.

  3. Modularity - Modules can be enabled/disabled, or even moved to separate assemblies.

  4. Testability - You can register just the modules needed for integration tests.

  5. Clean startup - Program.cs remains readable and high-level.