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

推荐订阅源

The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
Security Archives - TechRepublic
Security Archives - TechRepublic
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cisco Talos Blog
Cisco Talos Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
PCI Perspectives
PCI Perspectives
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
GbyAI
GbyAI
C
CERT Recently Published Vulnerability Notes
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
量子位
Scott Helme
Scott Helme
月光博客
月光博客
Attack and Defense Labs
Attack and Defense Labs
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
Project Zero
Project Zero
G
GRAHAM CLULEY
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
小众软件
小众软件
D
DataBreaches.Net
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
O
OpenAI News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
S
Security @ Cisco Blogs
The Last Watchdog
The Last Watchdog
MongoDB | Blog
MongoDB | Blog
H
Hacker News: Front Page
Latest news
Latest news
P
Proofpoint News Feed

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Introducing Kiwi DI: Simplifying Dependency Injection in .NET Ecosystems
Ajay Jain · 2026-05-06 · via DEV Community

Introduction to Kiwi DI

Kiwi DI (Kiwify.Kiwi.DependencyInjection) is an attribute-driven dependency injection framework for .NET. It moves service registration from startup code to the classes themselves, enabling config-driven activation, generic expansion, and declarative construction - all with a single AddKiwiServices call.


The Problem Kiwi DI Solves

Standard .NET DI registration works well at small scale. Five services, ten calls to AddScoped and AddSingleton, one startup entry point - manageable. But as an application grows, that startup code grows with it. At fifty services it is a maintenance problem. At one hundred, it is a liability.

The deeper issue is not the line count. It is the disconnection. A class exists in one file. Its DI registration exists in another. To understand how a class is wired-its lifetime, conditions, and interfaces-you have to look in multiple places. To add a feature flag that controls whether a service is active, you edit both the service and the startup code. To swap an implementation, you find and modify the startup block that wires it.

Kiwi DI inverts this relationship: the class declares its own registration rules. An attribute on the class says what its lifetime is, what conditions it depends on, and how it should be constructed. The framework reads those declarations at startup and wires everything automatically. Startup code becomes trivially short - one call - and stays that way regardless of how many services are added.


Source & Repository

Kiwi Config is open-source and available on GitHub:

https://github.com/kiwifylabs/kiwi-foundation-config-di


Installation

NuGet Package

<PackageReference Include="Kiwify.Kiwi.DependencyInjection" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" />

Enter fullscreen mode Exit fullscreen mode

Kiwify.Kiwi.Configuration is included transitively.

.NET CLI

dotnet add package Kiwify.Kiwi.DependencyInjection --version 1.0.0

Enter fullscreen mode Exit fullscreen mode

Related Articles


Source Code

https://github.com/kiwifylabs/kiwi-foundation-config-di

Quick Start

var services = new ServiceCollection();
services.AddKiwiServices(configuration);
var provider = services.BuildServiceProvider();

Enter fullscreen mode Exit fullscreen mode

That single call scans your assembly, loads all [ConfigService] config classes, and registers all [Service] classes - conditionally where specified.


Mental Model

Kiwi DI follows a simple model:

  • Classes declare what they are - lifetime, interfaces, and construction rules, expressed as attributes on the class itself.
  • Configuration declares when they are active - a config flag or named predicate controls whether a service enters the container.
  • The framework decides what gets wired - AddKiwiServices reads those declarations at startup and builds the container automatically.

Everything in this article maps back to one of these three responsibilities.


How AddKiwiServices Works

Before looking at individual attributes, it is worth understanding what AddKiwiServices actually does when you call it. Everything else flows from this.

services.AddKiwiServices(configuration);

Enter fullscreen mode Exit fullscreen mode

Internally, this runs four deterministic phases:

Phase 0 (pre-registration):
  Register any pre-loaded config instances passed via preLoadedConfigs

Phase 1 (config discovery):
  Scan assembly for classes carrying both [ConfigSection] and [ConfigService]
  For each: call LoadConfiguration<T>() and register the instance as a singleton

Phase 2 (temporary provider):
  Build a temporary IServiceProvider
  (All config singletons from Phase 1 are now resolvable)

Phase 3 (service discovery):
  Scan assembly for classes carrying [Service]
  For each: evaluate any conditions against the temporary provider
  Register passing services into the real container

Done - call BuildServiceProvider() normally

Enter fullscreen mode Exit fullscreen mode

The temporary provider built in Phase 2 exists only to evaluate conditions. It is never used for actual service resolution. It is discarded when AddKiwiServices returns. The final container is a standard IServiceProvider - Kiwi DI has no presence at runtime.


The Attributes

Kiwi DI uses four attributes. Each is placed on the class that it describes.

Attributes live in Kiwify.Kiwi.Platform.DependencyInjection.Attributes. Extension methods (AddKiwiServices, AddKiwiConfig, AddKiwiService) live in Kiwify.Kiwi.Platform.DependencyInjection.

using Kiwify.Kiwi.Platform.DependencyInjection;            // AddKiwiServices and friends
using Kiwify.Kiwi.Platform.DependencyInjection.Attributes; // [Service], [ConfigService], [RegistersFor], [ConstructFrom]

Enter fullscreen mode Exit fullscreen mode

Attribute Purpose
[ConfigService] Marks a config class for auto-loading and singleton registration
[Service(Lifetime)] Marks a service class for auto-registration
[RegistersFor(typeof(T))] Expands a generic class into concrete closed-generic registrations
[ConstructFrom(typeof(C), "Prop")] Injects scalar config property values as constructor arguments

[ConfigService] - Auto-Loading Configuration

[ConfigService] comes from this library but works together with [ConfigSection] from Kiwi Config. A class carrying both is discovered during Phase 1 and loaded as a config singleton.

using Kiwify.Kiwi.Platform.Configuration.Attributes;
using Kiwify.Kiwi.Platform.DependencyInjection;
using Kiwify.Kiwi.Platform.DependencyInjection.Attributes;

[ConfigSection("database")]   // from Kiwi Config - declares the config key
[ConfigService]               // from Kiwi DI - opts into auto-loading
public class DatabaseConfig
{
    [ConfigKey("host", "localhost")]
    public string Host { get; private set; } = string.Empty;

    [ConfigKey("port", 5432)]
    public int Port { get; private set; }

    [ConfigKey("name", Required = true)]
    public string Name { get; private set; } = string.Empty;
}

Enter fullscreen mode Exit fullscreen mode

After AddKiwiServices runs, DatabaseConfig is in the container as a singleton and can be injected normally:

[Service(ServiceLifetime.Scoped)]
public class OrderRepository
{
    private readonly DatabaseConfig _db;
    public OrderRepository(DatabaseConfig db) => _db = db;
}

Enter fullscreen mode Exit fullscreen mode

What [ConfigSection] alone does not do

[ConfigSection] tells Kiwi Config how to load the class. It says nothing about DI. Without [ConfigService], a class is invisible to AddKiwiServices - it still works with configuration.LoadConfiguration<T>() but is not auto-loaded into the container.

This separation matters: you can have config classes that are only ever loaded manually (e.g. before the container is built) without them appearing as singletons in the container.


[Service] - Registering a Service

[Service] marks a class for automatic registration. The required argument is the service lifetime.

[Service(ServiceLifetime.Singleton)]
public class GreetingService : IGreetingService { ... }

[Service(ServiceLifetime.Scoped)]
public class OrderService : IOrderService { ... }

[Service(ServiceLifetime.Transient)]
public class EmailFormatter : IEmailFormatter { ... }

Enter fullscreen mode Exit fullscreen mode

Interface resolution

By default, all non-System.* interfaces implemented by the class are registered automatically.

If a class implements no non-system interfaces, it is registered as its concrete type.

public interface IPaymentGateway { ... }
public interface IRetryable { ... }

[Service(ServiceLifetime.Singleton)]
public class StripeGateway : IPaymentGateway, IRetryable { ... }
// Registered as: IPaymentGateway and IRetryable

Enter fullscreen mode Exit fullscreen mode

Registering as self too

RegisterAsSelf = true adds the concrete type registration alongside the interface registrations. Useful when code needs to inject the concrete type directly - for example, when calling methods not on the interface.

[Service(ServiceLifetime.Singleton, RegisterAsSelf = true)]
public class MetricsCollector : IMetricsCollector { ... }
// Registered as: IMetricsCollector AND MetricsCollector

Enter fullscreen mode Exit fullscreen mode

Service lifetimes

Lifetime Created Disposed
Singleton Once per container When the container is disposed
Scoped Once per scope (per request in web apps) When the scope is disposed
Transient Every time it is resolved When the scope that created them is disposed (if tracked by the container)

Choose based on how much state the service holds and how long that state should live. Stateless services can be Singleton. Services that hold per-request state should be Scoped. Very lightweight, stateless objects can be Transient.


Multiple Implementations of the Same Interface

When two services implement the same interface and neither uses Key, both are registered:

[Service(ServiceLifetime.Singleton)]
public class ConsoleLogger : ILogger { ... }

[Service(ServiceLifetime.Singleton)]
public class FileLogger : ILogger { ... }

Enter fullscreen mode Exit fullscreen mode

  • GetRequiredService<ILogger>() returns the last registration (determined by discovery order, which depends on assembly metadata and should not be relied upon).
  • GetServices<ILogger>() returns all of them.

If you need deterministic resolution, use Key to give each implementation a distinct identity:

[Service(ServiceLifetime.Singleton, Key = "console")]
public class ConsoleLogger : ILogger { ... }

[Service(ServiceLifetime.Singleton, Key = "file")]
public class FileLogger : ILogger { ... }

Enter fullscreen mode Exit fullscreen mode

var console = provider.GetRequiredKeyedService<ILogger>("console");
var file    = provider.GetRequiredKeyedService<ILogger>("file");

Enter fullscreen mode Exit fullscreen mode


Conditional Registration: Config-Key Conditions

A service can declare a condition under which it should be registered. The most common form checks a configuration value.

[Service(ServiceLifetime.Singleton, ConfigKey = "Features:Redis")]
public class RedisCache : ICache { ... }

Enter fullscreen mode Exit fullscreen mode

This service is registered only when configuration["Features:Redis"] equals "true" (evaluated as a case-insensitive string comparison). The condition is evaluated in Phase 3, after all config singletons are loaded, using the temporary provider.

A different expected value:

[Service(ServiceLifetime.Singleton, ConfigKey = "Database:Type", ConfigValue = "postgres")]
public class PostgresRepository : IRepository { ... }

Enter fullscreen mode Exit fullscreen mode

This registers only when configuration["Database:Type"] == "postgres".

appsettings.json:

{
  "Features": { "Redis": "true" },
  "Database": { "Type": "postgres" }
}

Enter fullscreen mode Exit fullscreen mode


The Fallback Pattern: Negate = true

Negate = true inverts the condition. Combine it with the same condition on a second class to create a primary/fallback pair - exactly one of which is always registered.

// Primary: registered when Redis is enabled
[Service(ServiceLifetime.Singleton, ConfigKey = "Features:Redis")]
public class RedisCache : ICache { ... }

// Fallback: registered when Redis is NOT enabled
[Service(ServiceLifetime.Singleton, ConfigKey = "Features:Redis", Negate = true)]
public class InMemoryCache : ICache { ... }

Enter fullscreen mode Exit fullscreen mode

With Features:Redis = "true": only RedisCache is in the container.
With Features:Redis = "false" (or absent): only InMemoryCache is in the container.

The swap costs one config change. No startup code changes. No recompilation.

This pattern works for any number of implementations across any condition. You can also nest conditions or use the same flag for multiple service pairs.


Named Conditions: Complex Logic

Config flag checks cover common cases, but some conditions go beyond a single config value. Maybe a service should only be registered in the production environment. Maybe it requires credentials that might not be present. Maybe it checks a combination of conditions.

Named conditions are registered as predicates and referenced by name in the attribute.

services.AddKiwiServices(configuration, options =>
{
    options.AddCondition("IsProduction", sp =>
        sp.GetRequiredService<IHostEnvironment>().IsProduction());

    options.AddCondition("HasAzureCredentials", sp =>
    {
        var cfg = sp.GetRequiredService<IConfiguration>();
        return !string.IsNullOrEmpty(cfg["Azure:ConnectionString"]);
    });

    options.AddCondition("HighTrafficMode", sp =>
    {
        var appConfig = sp.GetRequiredService<AppConfig>();
        return appConfig.MaxConcurrency > 100;
    });
});

Enter fullscreen mode Exit fullscreen mode

The IServiceProvider passed to each predicate is the Phase 2 temporary provider - all config singletons are already available, so you can resolve them to inspect their values.

Referencing a named condition:

[Service(ServiceLifetime.Singleton, Condition = "IsProduction")]
public class ProductionMetrics : IMetrics { ... }

[Service(ServiceLifetime.Singleton, Condition = "IsProduction", Negate = true)]
public class NoOpMetrics : IMetrics { ... }

[Service(ServiceLifetime.Singleton, Condition = "HasAzureCredentials")]
public class AzureBlobStorage : IStorageService { ... }

[Service(ServiceLifetime.Scoped, Condition = "HighTrafficMode")]
public class BulkOrderProcessor : IOrderProcessor { ... }

Enter fullscreen mode Exit fullscreen mode

If both ConfigKey and Condition are set on the same [Service], Condition takes precedence. In practice, use one or the other - setting both invites ambiguity.


Keyed Services

Keyed services let multiple implementations of the same interface coexist, each retrievable by a string key.

[Service(ServiceLifetime.Scoped, Key = "primary")]
public class PrimaryDatabase : IDatabase { ... }

[Service(ServiceLifetime.Scoped, Key = "replica")]
public class ReplicaDatabase : IDatabase { ... }

Enter fullscreen mode Exit fullscreen mode

Resolution:

var primary = provider.GetRequiredKeyedService<IDatabase>("primary");
var replica  = provider.GetRequiredKeyedService<IDatabase>("replica");

Enter fullscreen mode Exit fullscreen mode

Keyed and conditional can be combined:

// Keyed primary/fallback - the key stays the same, the implementation swaps
[Service(ServiceLifetime.Scoped, Key = "cache", ConfigKey = "Features:Redis")]
public class RedisCache : ICache { ... }

[Service(ServiceLifetime.Scoped, Key = "cache", ConfigKey = "Features:Redis", Negate = true)]
public class InMemoryCache : ICache { ... }

Enter fullscreen mode Exit fullscreen mode

Callers always resolve by "cache" key - which implementation they get depends on the config flag.


Generic Services: [RegistersFor]

When the same pattern applies to multiple concrete types - event handlers, message processors, pipeline stages, notification senders - writing a separate registration for each concrete instantiation is repetitive.

[RegistersFor] lets one generic class declaration produce multiple concrete closed-generic registrations. Each attribute is one registration.

[Service(ServiceLifetime.Singleton)]
[RegistersFor(typeof(OrderHandler))]
[RegistersFor(typeof(PaymentHandler), Key = "payment")]
[RegistersFor(typeof(AuditHandler), Key = "audit", ConfigKey = "Features:Audit")]
public class EventManager<THandler> where THandler : class
{
    private readonly THandler _handler;

    public EventManager(THandler handler) => _handler = handler;

    public void Handle(object @event) { /* delegate to _handler */ }
}

Enter fullscreen mode Exit fullscreen mode

This single class produces:

  • EventManager<OrderHandler> - singleton, no key, always registered
  • EventManager<PaymentHandler> - singleton, keyed "payment", always registered
  • EventManager<AuditHandler> - singleton, keyed "audit", only if Features:Audit == "true"

Adding support for a new handler means adding one [RegistersFor] line. The startup code does not change.

Note: If a concrete type used in [RegistersFor] is itself conditionally registered, apply the same condition to the [RegistersFor] attribute. Otherwise, the generic wrapper can be registered while the dependency it wraps is absent from the container, causing a resolution failure at runtime.

// Good - condition on the generic registration matches the service it wraps
[RegistersFor(typeof(SmsHandler), Key = "sms", ConfigKey = "Features:Sms")]

Per-registration options

Each [RegistersFor] attribute can override the lifetime from [Service] and specify its own key, condition, and negate:

Property Purpose
concreteType The closed type argument (must not be a generic type definition)
Key Keyed registration key
Lifetime Override the parent [Service] lifetime for this registration
ConfigKey Config-flag condition
ConfigValue Expected value (default "true")
Condition Named condition reference
Negate Invert the condition

Generic type constraints

If the class has a type parameter constraint (: class, : new(), : ISomeInterface), the concrete type provided to [RegistersFor] is validated against it. An invalid type throws InvalidOperationException at startup.

public class EventManager<THandler> where THandler : class, IEventHandler
{
    ...
}

[RegistersFor(typeof(string))]  // throws - string does not satisfy IEventHandler constraint

Enter fullscreen mode Exit fullscreen mode


[ConstructFrom] - Scalar Values from Config

Standard constructor injection resolves entire services. Some components need raw scalar values from configuration - a port number, a connection string, a timeout - not a reference to the full config object.

Without [ConstructFrom], the only way to provide these is a factory lambda in startup code:

// Startup code - disconnected from the class that needs these values
services.AddSingleton(sp =>
{
    var cfg = sp.GetRequiredService<AppConfig>();
    return new TcpServer(cfg.Host, cfg.Port);
});

Enter fullscreen mode Exit fullscreen mode

[ConstructFrom] moves the extraction rule to the class itself:

[Service(ServiceLifetime.Singleton)]
[ConstructFrom(typeof(AppConfig), nameof(AppConfig.Host), nameof(AppConfig.Port))]
public class TcpServer
{
    private readonly string _host;
    private readonly int _port;

    public TcpServer(string host, int port)
    {
        _host = host;
        _port = port;
    }
}

Enter fullscreen mode Exit fullscreen mode

At resolve time, the framework:

  1. Resolves AppConfig from the container.
  2. Reads AppConfig.Host and AppConfig.Port in the order listed.
  3. Calls new TcpServer(host, port).

The startup code stays untouched.

Single property from one source

[Service(ServiceLifetime.Singleton)]
[ConstructFrom(typeof(DatabaseConfig), nameof(DatabaseConfig.ConnectionString))]
public class ConnectionPool
{
    public ConnectionPool(string connectionString) { ... }
}

Enter fullscreen mode Exit fullscreen mode

Multiple properties from one source

Properties are passed to the constructor in the order they are listed in the attribute:

[Service(ServiceLifetime.Singleton)]
[ConstructFrom(typeof(DatabaseConfig),
    nameof(DatabaseConfig.Host),
    nameof(DatabaseConfig.Port),
    nameof(DatabaseConfig.Name))]
public class DatabaseConnection
{
    public DatabaseConnection(string host, int port, string dbName) { ... }
}

Enter fullscreen mode Exit fullscreen mode

Multiple sources

Multiple [ConstructFrom] attributes are processed in declaration order. All properties from the first attribute become the first constructor arguments, then the second, and so on:

[Service(ServiceLifetime.Scoped)]
[ConstructFrom(typeof(DatabaseConfig), nameof(DatabaseConfig.ConnectionString))]  // arg 0
[ConstructFrom(typeof(CacheConfig),    nameof(CacheConfig.RedisEndpoint))]         // arg 1
[ConstructFrom(typeof(AppConfig),      nameof(AppConfig.InstanceId))]              // arg 2
public class DataCoordinator
{
    public DataCoordinator(string connStr, string redisEndpoint, string instanceId) { ... }
}

Enter fullscreen mode Exit fullscreen mode

When to use vs regular injection

Scenario Approach
Service needs specific scalar values (port, timeout, connection string) [ConstructFrom]
Service needs to call methods on the config object Regular injection - inject the config class
Service needs both scalar config values and other services Regular injection - let the service extract what it needs
Factory logic is too complex for property extraction Manual services.Add*(sp => ...)

Constraint to know

Important: A class using [ConstructFrom] cannot also use regular DI constructor injection. All constructor arguments must come from property extraction. If a class needs both scalar config values and injected services, inject the full config object instead.


Pre-Loaded Configs

Sometimes you need configuration values before the DI container is built - to configure the logging pipeline, set up middleware, or make decisions before AddKiwiServices is called.

Load the config manually and use it immediately:

// Load before the container exists
var appConfig = configuration.LoadConfiguration<AppConfig>();

// Use the values pre-container
SetupLogging(appConfig.LogLevel);
ConfigureListenAddress(appConfig.Port);

// Pass the already-loaded instance to AddKiwiServices
// It skips auto-loading for that type and registers the provided instance as the singleton
services.AddKiwiServices(configuration, preLoadedConfigs: appConfig);

Enter fullscreen mode Exit fullscreen mode

Services that inject AppConfig receive the same instance loaded before the container was built.

Multiple pre-loaded configs:

var appConfig = configuration.LoadConfiguration<AppConfig>();
var dbConfig  = configuration.LoadConfiguration<DatabaseConfig>();

services.AddKiwiServices(configuration,
    preLoadedConfigs: new object[] { appConfig, dbConfig });

Enter fullscreen mode Exit fullscreen mode

All other [ConfigService] types in the assembly are still auto-loaded normally. Only the pre-loaded types are skipped (since they are already registered).


Manual Registration

For selective control without a full assembly scan, use the single-type registration methods:

// Register a single config class
services.AddKiwiConfig<DatabaseConfig>(configuration);

// Register a single service
services.AddKiwiService<OrderService>();

Enter fullscreen mode Exit fullscreen mode

AddKiwiConfig<T> validates [ConfigSection] and [ConfigService], calls LoadConfiguration<T>, and registers the result as a singleton.

AddKiwiService<T> validates [Service], resolves constructor dependencies recursively, and registers the service.

These are useful in tests, in tools that do not scan entire assemblies, or when integrating Kiwi DI incrementally into an existing codebase.


Using Kiwi Config and Kiwi DI Together

The two libraries are designed to work together, but each can be used independently. When used together, AddKiwiServices handles the entire coordination:

// Program.cs

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();

var services = new ServiceCollection();
services.AddKiwiServices(configuration);
var provider = services.BuildServiceProvider();

Enter fullscreen mode Exit fullscreen mode

Config classes annotated with both [ConfigSection] and [ConfigService] are loaded from configuration and become injectable singletons. Service classes annotated with [Service] can inject those config singletons through normal constructor injection because the config singletons are registered first (Phase 1 before Phase 3).

[ConfigSection("app")]
[ConfigService]
public class AppConfig
{
    [ConfigKey("name", "MyApp")]
    public string Name { get; private set; } = string.Empty;

    [ConfigKey("port", 5000)]
    public int Port { get; private set; }
}

[Service(ServiceLifetime.Singleton)]
public class AppServer : IAppServer
{
    private readonly AppConfig _config;

    public AppServer(AppConfig config) => _config = config;

    public void Start() => Console.WriteLine($"Starting {_config.Name} on port {_config.Port}");
}

Enter fullscreen mode Exit fullscreen mode

services.AddKiwiServices(configuration);
var provider = services.BuildServiceProvider();
provider.GetRequiredService<IAppServer>().Start();
// Starting MyApp on port 5000

Enter fullscreen mode Exit fullscreen mode

No factory, no registration block, no startup code changes when new services are added.


Complete End-to-End Example

A realistic notification system demonstrating config loading, conditional services, the fallback pattern, generic expansion, and [ConstructFrom] - all wired together with a single AddKiwiServices call.

Configuration

appsettings.json (all configuration values are treated as strings):

{
  "notifications": {
    "smtpHost": "mail.example.com",
    "retryCount": 3
  },
  "Features": {
    "Sms": "false",
    "Audit": "true"
  }
}

Enter fullscreen mode Exit fullscreen mode

Config class

[ConfigSection("notifications")]
[ConfigService]
public class NotificationConfig
{
    [ConfigKey("smtpHost", Required = true)]
    public string SmtpHost { get; private set; } = string.Empty;

    [ConfigKey("retryCount", 3)]
    public int RetryCount { get; private set; }
}

Enter fullscreen mode Exit fullscreen mode

Conditional services - SMS or email based on config

public interface INotificationSender
{
    void Send(string to, string body);
}

// Active only when Features:Sms = "true"
[Service(ServiceLifetime.Scoped, ConfigKey = "Features:Sms")]
public class SmsNotificationSender : INotificationSender
{
    public void Send(string to, string body)
        => Console.WriteLine($"[SMS] {to}: {body}");
}

// Active when Features:Sms is not "true" (the fallback)
[Service(ServiceLifetime.Scoped, ConfigKey = "Features:Sms", Negate = true)]
public class EmailNotificationSender : INotificationSender
{
    private readonly string _smtpHost;

    public EmailNotificationSender(NotificationConfig config)
        => _smtpHost = config.SmtpHost;

    public void Send(string to, string body)
        => Console.WriteLine($"[Email via {_smtpHost}] {to}: {body}");
}

Enter fullscreen mode Exit fullscreen mode

With Features:Sms = "false", only EmailNotificationSender enters the container.

Retry handler - scalar value from config via [ConstructFrom]

[Service(ServiceLifetime.Singleton)]
[ConstructFrom(typeof(NotificationConfig), nameof(NotificationConfig.RetryCount))]
public class RetryHandler
{
    private readonly int _retryCount;

    public RetryHandler(int retryCount) => _retryCount = retryCount;

    public void Execute(Action action)
    {
        for (var i = 0; i <= _retryCount; i++)
        {
            try { action(); return; }
            catch when (i < _retryCount) { }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

RetryHandler receives the RetryCount = 3 value extracted directly from NotificationConfig - no reference to the full config object needed.

Generic processor - one class, two registrations

[Service(ServiceLifetime.Scoped)]
[RegistersFor(typeof(SmsNotificationSender),   Key = "sms",   ConfigKey = "Features:Sms")]
[RegistersFor(typeof(EmailNotificationSender), Key = "email", ConfigKey = "Features:Sms", Negate = true)]
public class NotificationProcessor<TSender>
    where TSender : class, INotificationSender
{
    private readonly TSender _sender;
    private readonly RetryHandler _retry;

    public NotificationProcessor(TSender sender, RetryHandler retry)
    {
        _sender = sender;
        _retry  = retry;
    }

    public void Notify(string to, string body)
        => _retry.Execute(() => _sender.Send(to, body));
}

Enter fullscreen mode Exit fullscreen mode

This produces:

  • NotificationProcessor<SmsNotificationSender> registered under key "sms"
  • NotificationProcessor<EmailNotificationSender> registered under key "email"

Audit service - named condition example

services.AddKiwiServices(configuration, options =>
{
    options.AddCondition("AuditEnabled", sp =>
    {
        var cfg = sp.GetRequiredService<IConfiguration>();
        return cfg["Features:Audit"] == "true";
    });
});

[Service(ServiceLifetime.Singleton, Condition = "AuditEnabled")]
public class AuditLogger : IAuditLogger
{
    public void Log(string action) => Console.WriteLine($"[AUDIT] {action}");
}

[Service(ServiceLifetime.Singleton, Condition = "AuditEnabled", Negate = true)]
public class NoOpAuditLogger : IAuditLogger
{
    public void Log(string action) { }
}

Enter fullscreen mode Exit fullscreen mode

Startup and usage

services.AddKiwiServices(configuration, options =>
{
    options.AddCondition("AuditEnabled", sp =>
        sp.GetRequiredService<IConfiguration>()["Features:Audit"] == "true");
});

var provider = services.BuildServiceProvider();

// With Features:Sms = "false" and Features:Audit = "true":
var emailProcessor = provider.GetRequiredKeyedService<NotificationProcessor<EmailNotificationSender>>("email");
emailProcessor.Notify("user@example.com", "Your order has shipped.");
// [Email via mail.example.com] user@example.com: Your order has shipped.

var audit = provider.GetRequiredService<IAuditLogger>();
audit.Log("Notification sent");
// [AUDIT] Notification sent

Enter fullscreen mode Exit fullscreen mode

What AddKiwiServices did:

  1. Loaded NotificationConfig → registered as singleton (SmtpHost = mail.example.com, RetryCount = 3).
  2. Evaluated Features:Sms = "false" → registered EmailNotificationSender; skipped SmsNotificationSender.
  3. Registered RetryHandler as singleton - extracted RetryCount = 3 from NotificationConfig.
  4. Evaluated Features:Sms = "false" → registered NotificationProcessor<EmailNotificationSender> (key "email"); skipped NotificationProcessor<SmsNotificationSender> (key "sms") because its condition mirrors that of SmsNotificationSender.
  5. Evaluated named condition AuditEnabled → registered AuditLogger; skipped NoOpAuditLogger.

To switch to SMS: set Features:Sms = "true". To disable auditing: set Features:Audit = "false". The swap is a config change. No startup edits. No recompilation.


Performance and Startup Cost

Kiwi DI shifts all discovery and wiring work to startup so runtime remains identical to standard .NET DI. All reflection and assembly scanning happens exactly once - at startup - and contributes nothing to runtime latency.

Step When Notes
Assembly type scanning Startup Proportional to assembly size; typically well under 100ms for a few hundred types (depending on environment)
Config loading (per class) Startup Reflection-based; negligible for typical class sizes
Temporary provider build Startup One extra BuildServiceProvider() call
Condition evaluation Startup One predicate call per conditional service
Service resolution at runtime Runtime Standard .NET DI - no Kiwi reflection involved

If assembly scanning of very large assemblies causes noticeable startup delay, pass explicit assemblies to narrow the scope:

services.AddKiwiServices(configuration, assemblies: new[]
{
    typeof(OrderService).Assembly,
    typeof(PaymentService).Assembly
});

Enter fullscreen mode Exit fullscreen mode


When to Use Kiwi DI

Use it when:

  • Your application has a meaningful number of services and startup registration has become a maintenance concern.
  • You want config-driven feature flags to control service activation without touching startup code.
  • You use generic processor or handler patterns where one class is instantiated for many concrete types.
  • You value co-location: the DI role of a class is visible at the class, not buried in startup code.

Consider alternatives when:

  • Your application is small (roughly fewer than 20-30 services). The attribute indirection adds complexity that manual registration does not, and the savings are minimal.
  • You need fine-grained control over registration order or multi-step factory chains that do not map to attribute declarations.
  • Your team prefers fully explicit, line-by-line startup code as a policy.
  • You are debugging complex DI graph issues and want the simplest possible dependency graph.

Feature Summary

Goal How
Auto-load a config class into DI [ConfigSection] + [ConfigService] on the class
Register a service [Service(Lifetime)] on the class
Also register as concrete type RegisterAsSelf = true
Register only when a config flag is set ConfigKey = "Section:Key"
Register only when a flag is NOT set ConfigKey = "..." + Negate = true
Register based on complex logic options.AddCondition("name", sp => ...) + Condition = "name"
Fallback when condition fails Negate = true (same condition)
Keyed registration Key = "myKey"
Resolve keyed service provider.GetRequiredKeyedService<T>("myKey")
One generic class → many registrations [RegistersFor(typeof(T))] (multiple attributes)
Scalar config values as constructor args [ConstructFrom(typeof(Config), "Prop1", "Prop2")]
Load config before container is built configuration.LoadConfiguration<T>() then preLoadedConfigs: instance
Register one class manually services.AddKiwiConfig<T>() or services.AddKiwiService<T>()
Named conditions from external logic options.AddCondition(name, sp => bool)