|
| 1 | +# Constructor Dependency Injection |
| 2 | + |
| 3 | +This document describes the new constructor dependency injection capabilities added to the xUnit Dependency Injection framework while maintaining full backward compatibility with the existing fixture-based approach. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The framework now supports two approaches for dependency injection: |
| 8 | + |
| 9 | +1. **Traditional Fixture-Based Approach** (existing) - Access services via `_fixture.GetService<T>(_testOutputHelper)` |
| 10 | +2. **Constructor Dependency Injection** (new) - Inject services directly into test class properties during construction |
| 11 | + |
| 12 | +## Property Injection with TestBedWithDI |
| 13 | + |
| 14 | +### Basic Usage |
| 15 | + |
| 16 | +Inherit from `TestBedWithDI<TFixture>` instead of `TestBed<TFixture>` and use the `[Inject]` attribute on properties: |
| 17 | + |
| 18 | +```csharp |
| 19 | +public class PropertyInjectionTests : TestBedWithDI<TestProjectFixture> |
| 20 | +{ |
| 21 | + [Inject] |
| 22 | + public ICalculator? Calculator { get; set; } |
| 23 | + |
| 24 | + [Inject] |
| 25 | + public IOptions<Options>? Options { get; set; } |
| 26 | + |
| 27 | + public PropertyInjectionTests(ITestOutputHelper testOutputHelper, TestProjectFixture fixture) |
| 28 | + : base(testOutputHelper, fixture) |
| 29 | + { |
| 30 | + // Dependencies are automatically injected after base constructor completes |
| 31 | + } |
| 32 | + |
| 33 | + [Fact] |
| 34 | + public async Task TestCalculatorThroughPropertyInjection() |
| 35 | + { |
| 36 | + // Dependencies are already available - no need to call _fixture methods |
| 37 | + Assert.NotNull(Calculator); |
| 38 | + Assert.NotNull(Options); |
| 39 | + |
| 40 | + var result = await Calculator.AddAsync(5, 3); |
| 41 | + var expected = Options.Value.Rate * (5 + 3); |
| 42 | + Assert.Equal(expected, result); |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +### Keyed Services |
| 48 | + |
| 49 | +Use the `[Inject("key")]` attribute for keyed services: |
| 50 | + |
| 51 | +```csharp |
| 52 | +public class PropertyInjectionTests : TestBedWithDI<TestProjectFixture> |
| 53 | +{ |
| 54 | + [Inject("Porsche")] |
| 55 | + internal ICarMaker? PorscheCarMaker { get; set; } |
| 56 | + |
| 57 | + [Inject("Toyota")] |
| 58 | + internal ICarMaker? ToyotaCarMaker { get; set; } |
| 59 | + |
| 60 | + [Fact] |
| 61 | + public void TestKeyedServicesThroughPropertyInjection() |
| 62 | + { |
| 63 | + Assert.NotNull(PorscheCarMaker); |
| 64 | + Assert.NotNull(ToyotaCarMaker); |
| 65 | + Assert.Equal("Porsche", PorscheCarMaker.Manufacturer); |
| 66 | + Assert.Equal("Toyota", ToyotaCarMaker.Manufacturer); |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +### Convenience Methods |
| 72 | + |
| 73 | +The `TestBedWithDI` class provides convenience methods that don't require the `_testOutputHelper` parameter: |
| 74 | + |
| 75 | +```csharp |
| 76 | +protected T? GetService<T>() |
| 77 | +protected T? GetScopedService<T>() |
| 78 | +protected T? GetKeyedService<T>(string key) |
| 79 | +``` |
| 80 | + |
| 81 | +```csharp |
| 82 | +[Theory] |
| 83 | +[InlineData(10, 20)] |
| 84 | +public async Task TestConvenienceMethodsStillWork(int x, int y) |
| 85 | +{ |
| 86 | + // These methods are available without needing _fixture |
| 87 | + var calculator = GetService<ICalculator>(); |
| 88 | + var options = GetService<IOptions<Options>>(); |
| 89 | + var porsche = GetKeyedService<ICarMaker>("Porsche"); |
| 90 | + |
| 91 | + Assert.NotNull(calculator); |
| 92 | + Assert.NotNull(options); |
| 93 | + Assert.NotNull(porsche); |
| 94 | +} |
| 95 | +``` |
| 96 | + |
| 97 | +## Factory-Based Constructor Injection (Experimental) |
| 98 | + |
| 99 | +For true constructor injection, use `TestBedFactoryFixture` with the factory pattern: |
| 100 | + |
| 101 | +### Setup |
| 102 | + |
| 103 | +```csharp |
| 104 | +public class FactoryTestProjectFixture : TestBedFactoryFixture |
| 105 | +{ |
| 106 | + protected override void AddServices(IServiceCollection services, IConfiguration? configuration) |
| 107 | + => services |
| 108 | + .AddTransient<ICalculator, Calculator>() |
| 109 | + .AddKeyedTransient<ICarMaker, Porsche>("Porsche") |
| 110 | + .AddKeyedTransient<ICarMaker, Toyota>("Toyota") |
| 111 | + .AddTransient<SimpleService>(); // Register classes that need constructor injection |
| 112 | +} |
| 113 | +``` |
| 114 | + |
| 115 | +### Usage |
| 116 | + |
| 117 | +```csharp |
| 118 | +public class FactoryConstructorInjectionTests : TestBed<FactoryTestProjectFixture> |
| 119 | +{ |
| 120 | + [Fact] |
| 121 | + public async Task TestConstructorInjectionViaFactory() |
| 122 | + { |
| 123 | + // Create instances with constructor injection |
| 124 | + var simpleService = _fixture.CreateTestInstance<SimpleService>(_testOutputHelper); |
| 125 | + |
| 126 | + var result = await simpleService.CalculateAsync(10, 5); |
| 127 | + Assert.True(result > 0); |
| 128 | + } |
| 129 | +} |
| 130 | +``` |
| 131 | + |
| 132 | +### Service Class with Constructor Injection |
| 133 | + |
| 134 | +```csharp |
| 135 | +public class SimpleService |
| 136 | +{ |
| 137 | + private readonly ICalculator _calculator; |
| 138 | + private readonly Options _options; |
| 139 | + |
| 140 | + public SimpleService(ICalculator calculator, IOptions<Options> options) |
| 141 | + { |
| 142 | + _calculator = calculator ?? throw new ArgumentNullException(nameof(calculator)); |
| 143 | + _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); |
| 144 | + } |
| 145 | + |
| 146 | + public async Task<int> CalculateAsync(int x, int y) |
| 147 | + { |
| 148 | + return await _calculator.AddAsync(x, y); |
| 149 | + } |
| 150 | +} |
| 151 | +``` |
| 152 | + |
| 153 | +### Keyed Services in Factory Pattern |
| 154 | + |
| 155 | +Use the `[FromKeyedService("key")]` attribute for keyed service constructor parameters: |
| 156 | + |
| 157 | +```csharp |
| 158 | +public class CalculatorService |
| 159 | +{ |
| 160 | + public CalculatorService( |
| 161 | + ICalculator calculator, |
| 162 | + IOptions<Options> options, |
| 163 | + [FromKeyedService("Porsche")] ICarMaker porsche, |
| 164 | + [FromKeyedService("Toyota")] ICarMaker toyota) |
| 165 | + { |
| 166 | + // Constructor injection with keyed services |
| 167 | + } |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +## Backward Compatibility |
| 172 | + |
| 173 | +All existing code continues to work unchanged. The new approaches are additive: |
| 174 | + |
| 175 | +- `TestBed<TFixture>` continues to work as before |
| 176 | +- `_fixture.GetService<T>(_testOutputHelper)` methods work as before |
| 177 | +- Existing test classes require no changes |
| 178 | + |
| 179 | +## Migration Path |
| 180 | + |
| 181 | +You can migrate existing tests gradually: |
| 182 | + |
| 183 | +1. **Option 1**: Keep using `TestBed<TFixture>` with existing fixture methods |
| 184 | +2. **Option 2**: Change to `TestBedWithDI<TFixture>` and use `[Inject]` properties for new dependencies while keeping existing fixture method calls |
| 185 | +3. **Option 3**: Fully migrate to property injection for cleaner test code |
| 186 | + |
| 187 | +## Benefits |
| 188 | + |
| 189 | +### Property Injection Approach |
| 190 | +- ✅ Clean, declarative syntax |
| 191 | +- ✅ No need to pass `_testOutputHelper` around |
| 192 | +- ✅ Dependencies available immediately in test methods |
| 193 | +- ✅ Full support for regular and keyed services |
| 194 | +- ✅ Maintains all existing fixture capabilities |
| 195 | +- ✅ Works perfectly with xUnit lifecycle |
| 196 | + |
| 197 | +### Factory Approach |
| 198 | +- ✅ True constructor injection for service classes |
| 199 | +- ✅ Works for regular services and additional parameters |
| 200 | +- ⚠️ Keyed services support is experimental |
| 201 | +- ⚠️ More complex setup required |
| 202 | + |
| 203 | +## Recommendation |
| 204 | + |
| 205 | +Use the **Property Injection with TestBedWithDI** approach for most scenarios as it provides the cleanest developer experience while maintaining full compatibility with the existing framework. |
0 commit comments