|
| 1 | +# Instance Registrations |
| 2 | + |
| 3 | +DecoWeaver supports decorating singleton instance registrations starting with version 1.0.4-beta. This allows you to apply decorators to pre-configured instances that you register directly with the DI container. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +Instance registrations let you register a pre-created instance directly with the DI container. DecoWeaver can intercept these registrations and apply decorators around your instance, just like it does for parameterless and factory delegate registrations. |
| 8 | + |
| 9 | +## Supported Patterns |
| 10 | + |
| 11 | +### Single Type Parameter with Instance |
| 12 | + |
| 13 | +```csharp |
| 14 | +// Register a pre-created instance |
| 15 | +var instance = new SqlRepository<Customer>(); |
| 16 | +services.AddSingleton<IRepository<Customer>>(instance); |
| 17 | + |
| 18 | +// DecoWeaver will apply decorators around the instance |
| 19 | +var repo = serviceProvider.GetRequiredService<IRepository<Customer>>(); |
| 20 | +// Returns: LoggingRepository<Customer> wrapping SqlRepository<Customer> instance |
| 21 | +``` |
| 22 | + |
| 23 | +### Keyed Instance Registration |
| 24 | + |
| 25 | +```csharp |
| 26 | +// Register a pre-created instance with a key |
| 27 | +var instance = new SqlRepository<Customer>(); |
| 28 | +services.AddKeyedSingleton<IRepository<Customer>>("primary", instance); |
| 29 | + |
| 30 | +// Resolve using the same key |
| 31 | +var repo = serviceProvider.GetRequiredKeyedService<IRepository<Customer>>("primary"); |
| 32 | +// Returns: LoggingRepository<Customer> wrapping SqlRepository<Customer> instance |
| 33 | +``` |
| 34 | + |
| 35 | +## Limitations |
| 36 | + |
| 37 | +### Singleton Only |
| 38 | + |
| 39 | +Instance registrations are **only supported with `AddSingleton`**. This is a limitation of .NET's dependency injection framework itself: |
| 40 | + |
| 41 | +```csharp |
| 42 | +// ✅ Supported - AddSingleton with instance |
| 43 | +services.AddSingleton<IRepository<Customer>>(instance); |
| 44 | + |
| 45 | +// ❌ NOT supported - AddScoped doesn't have instance overload in .NET DI |
| 46 | +services.AddScoped<IRepository<Customer>>(instance); // Compiler error |
| 47 | +
|
| 48 | +// ❌ NOT supported - AddTransient doesn't have instance overload in .NET DI |
| 49 | +services.AddTransient<IRepository<Customer>>(instance); // Compiler error |
| 50 | +``` |
| 51 | + |
| 52 | +The reason is that scoped and transient lifetimes are incompatible with instance registrations - they require creating new instances on each resolution or scope, which contradicts the concept of registering a pre-created instance. |
| 53 | + |
| 54 | +## How It Works |
| 55 | + |
| 56 | +When DecoWeaver encounters an instance registration: |
| 57 | + |
| 58 | +1. **Instance Type Extraction**: The generator extracts the actual type of the instance from the argument expression |
| 59 | + ```csharp |
| 60 | + // User code: |
| 61 | + services.AddSingleton<IRepository<Customer>>(new SqlRepository<Customer>()); |
| 62 | + |
| 63 | + // DecoWeaver sees: |
| 64 | + // - Service type: IRepository<Customer> |
| 65 | + // - Implementation type: SqlRepository<Customer> (extracted from "new SqlRepository<Customer>()") |
| 66 | + ``` |
| 67 | + |
| 68 | +2. **Keyed Service Registration**: The instance is registered directly as a keyed service |
| 69 | + ```csharp |
| 70 | + // Generated code: |
| 71 | + var key = DecoratorKeys.For(typeof(IRepository<Customer>), typeof(SqlRepository<Customer>)); |
| 72 | + var capturedInstance = (IRepository<Customer>)(object)implementationInstance; |
| 73 | + services.AddKeyedSingleton<IRepository<Customer>>(key, capturedInstance); |
| 74 | + ``` |
| 75 | + |
| 76 | +3. **Decorator Application**: Decorators are applied around the keyed service |
| 77 | + ```csharp |
| 78 | + // Generated code: |
| 79 | + services.AddSingleton<IRepository<Customer>>(sp => |
| 80 | + { |
| 81 | + var current = sp.GetRequiredKeyedService<IRepository<Customer>>(key); |
| 82 | + current = (IRepository<Customer>)DecoratorFactory.Create( |
| 83 | + sp, typeof(IRepository<Customer>), typeof(LoggingRepository<>), current); |
| 84 | + return current; |
| 85 | + }); |
| 86 | + ``` |
| 87 | + |
| 88 | +## Examples |
| 89 | + |
| 90 | +### Basic Instance Registration |
| 91 | + |
| 92 | +```csharp |
| 93 | +[DecoratedBy<LoggingRepository<>>] |
| 94 | +public class SqlRepository<T> : IRepository<T> |
| 95 | +{ |
| 96 | + public void Save(T entity) |
| 97 | + { |
| 98 | + Console.WriteLine($"[SQL] Saving {typeof(T).Name}..."); |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +// Register pre-created instance |
| 103 | +var instance = new SqlRepository<Customer>(); |
| 104 | +services.AddSingleton<IRepository<Customer>>(instance); |
| 105 | + |
| 106 | +// The same instance is reused for all resolutions, but wrapped with decorators |
| 107 | +var repo1 = serviceProvider.GetRequiredService<IRepository<Customer>>(); |
| 108 | +var repo2 = serviceProvider.GetRequiredService<IRepository<Customer>>(); |
| 109 | +// repo1 and repo2 both wrap the same SqlRepository<Customer> instance |
| 110 | +``` |
| 111 | + |
| 112 | +### Multiple Decorators with Instance |
| 113 | + |
| 114 | +```csharp |
| 115 | +[DecoratedBy<CachingRepository<>>(Order = 1)] |
| 116 | +[DecoratedBy<LoggingRepository<>>(Order = 2)] |
| 117 | +public class SqlRepository<T> : IRepository<T> { /* ... */ } |
| 118 | + |
| 119 | +var instance = new SqlRepository<Product>(); |
| 120 | +services.AddSingleton<IRepository<Product>>(instance); |
| 121 | + |
| 122 | +// Resolved as: LoggingRepository wrapping CachingRepository wrapping instance |
| 123 | +``` |
| 124 | + |
| 125 | +### Pre-Configured Instance |
| 126 | + |
| 127 | +```csharp |
| 128 | +// Useful when instance needs complex initialization |
| 129 | +var connectionString = configuration.GetConnectionString("Production"); |
| 130 | +var instance = new SqlRepository<Order>(connectionString) |
| 131 | +{ |
| 132 | + CommandTimeout = TimeSpan.FromSeconds(30), |
| 133 | + EnableRetries = true |
| 134 | +}; |
| 135 | + |
| 136 | +services.AddSingleton<IRepository<Order>>(instance); |
| 137 | +// Decorators are applied, but the pre-configured instance is preserved |
| 138 | +``` |
| 139 | + |
| 140 | +### Keyed Instance with Multiple Configurations |
| 141 | + |
| 142 | +```csharp |
| 143 | +[DecoratedBy<LoggingRepository<>>] |
| 144 | +public class SqlRepository<T> : IRepository<T> { /* ... */ } |
| 145 | + |
| 146 | +// Register multiple instances with different configurations |
| 147 | +var primaryDb = new SqlRepository<Customer>("Server=primary;Database=Main"); |
| 148 | +var secondaryDb = new SqlRepository<Customer>("Server=secondary;Database=Replica"); |
| 149 | + |
| 150 | +services.AddKeyedSingleton<IRepository<Customer>>("primary", primaryDb); |
| 151 | +services.AddKeyedSingleton<IRepository<Customer>>("secondary", secondaryDb); |
| 152 | + |
| 153 | +// Each key resolves its own instance with decorators applied |
| 154 | +var primary = serviceProvider.GetRequiredKeyedService<IRepository<Customer>>("primary"); |
| 155 | +var secondary = serviceProvider.GetRequiredKeyedService<IRepository<Customer>>("secondary"); |
| 156 | +// Both are wrapped with LoggingRepository, but use different SqlRepository instances |
| 157 | +``` |
| 158 | + |
| 159 | +## Technical Details |
| 160 | + |
| 161 | +### Type Extraction from Arguments |
| 162 | + |
| 163 | +DecoWeaver uses Roslyn's semantic model to extract the actual type from the instance argument: |
| 164 | + |
| 165 | +```csharp |
| 166 | +// In ClosedGenericRegistrationProvider.cs - Non-keyed instance |
| 167 | +var args = inv.ArgumentList.Arguments; |
| 168 | +if (args.Count >= 1) |
| 169 | +{ |
| 170 | + var instanceArg = args[0].Expression; // Extension methods don't include 'this' in ArgumentList |
| 171 | + var instanceType = semanticModel.GetTypeInfo(instanceArg).Type as INamedTypeSymbol; |
| 172 | + return (serviceType, instanceType); // e.g., (IRepository<Customer>, SqlRepository<Customer>) |
| 173 | +} |
| 174 | + |
| 175 | +// For keyed instances |
| 176 | +if (args.Count >= 2) // Key parameter + instance parameter |
| 177 | +{ |
| 178 | + var instanceArg = args[1].Expression; // Second argument after the key |
| 179 | + var instanceType = semanticModel.GetTypeInfo(instanceArg).Type as INamedTypeSymbol; |
| 180 | + return (serviceType, instanceType); |
| 181 | +} |
| 182 | +``` |
| 183 | + |
| 184 | +### Direct Instance Registration |
| 185 | + |
| 186 | +DecoWeaver uses the direct instance overload available in .NET DI for keyed singleton services: |
| 187 | + |
| 188 | +```csharp |
| 189 | +// DecoWeaver generates: |
| 190 | +var key = DecoratorKeys.For(typeof(IRepository<Customer>), typeof(SqlRepository<Customer>)); |
| 191 | +var capturedInstance = (IRepository<Customer>)(object)implementationInstance; |
| 192 | +services.AddKeyedSingleton<IRepository<Customer>>(key, capturedInstance); |
| 193 | +``` |
| 194 | + |
| 195 | +This preserves the expected .NET DI disposal semantics - the container owns and disposes the instance when the container is disposed, just like non-keyed singleton instance registrations. |
| 196 | + |
| 197 | +The double cast `(TService)(object)` ensures the generic type parameter `TService` is compatible with the captured instance. |
| 198 | + |
| 199 | +## When to Use Instance Registrations |
| 200 | + |
| 201 | +Instance registrations with DecoWeaver are useful when: |
| 202 | + |
| 203 | +1. **Pre-configured Dependencies**: Your instance needs complex initialization that's easier to do outside of DI |
| 204 | +2. **External Resources**: Registering wrappers around external resources (e.g., database connections, message queues) |
| 205 | +3. **Testing/Mocking**: Registering test doubles or mocks with specific configurations |
| 206 | +4. **Singleton State**: When you need a true singleton with decorators applied |
| 207 | + |
| 208 | +## Alternatives |
| 209 | + |
| 210 | +If you need more flexibility, consider these alternatives: |
| 211 | + |
| 212 | +### Factory Delegates |
| 213 | +```csharp |
| 214 | +// More flexible than instances - can use IServiceProvider |
| 215 | +services.AddSingleton<IRepository<Customer>>(sp => |
| 216 | +{ |
| 217 | + var config = sp.GetRequiredService<IConfiguration>(); |
| 218 | + return new SqlRepository<Customer>(config.GetConnectionString("Default")); |
| 219 | +}); |
| 220 | +``` |
| 221 | + |
| 222 | +### Parameterless with Constructor Injection |
| 223 | +```csharp |
| 224 | +// Let DI handle the construction |
| 225 | +services.AddSingleton<IRepository<Customer>, SqlRepository<Customer>>(); |
| 226 | +// SqlRepository constructor receives dependencies from DI |
| 227 | +``` |
| 228 | + |
| 229 | +## See Also |
| 230 | + |
| 231 | +- [Factory Delegates](../usage/factory-delegates.md) - Using factory functions with decorators |
| 232 | +- [Keyed Services](keyed-services.md) - How DecoWeaver uses keyed services internally |
| 233 | +- [How It Works](../core-concepts/how-it-works.md) - Understanding the generation process |
0 commit comments