Add DI support for RecDbContext with configuration options
Introduced a `DependencyInjection` class with an extension method `AddInfrastructureServices` to register `RecDbContext` using configurable `DbContextOptions`. Added a `ConfigurationOptions` class to encapsulate `DbContext` configuration. Validated that `DbContextOptionsAction` is provided before registration. Updated `ReC.Infrastructure.csproj` to include `Microsoft.Extensions.Configuration.Abstractions` for enhanced configuration support. Added necessary `using` directives.
This commit is contained in:
31
src/ReC.Infrastructure/DependencyInjection.cs
Normal file
31
src/ReC.Infrastructure/DependencyInjection.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace ReC.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, Action<ConfigurationOptions> options)
|
||||
{
|
||||
var configOpt = new ConfigurationOptions();
|
||||
options.Invoke(configOpt);
|
||||
|
||||
if(configOpt.DbContextOptionsAction is null)
|
||||
throw new InvalidOperationException("DbContextOptionsAction must be configured.");
|
||||
|
||||
services.AddDbContext<RecDbContext>(configOpt.DbContextOptionsAction);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public class ConfigurationOptions
|
||||
{
|
||||
internal Action<DbContextOptionsBuilder>? DbContextOptionsAction { get; private set; }
|
||||
|
||||
public ConfigurationOptions ConfigureDbContext(Action<DbContextOptionsBuilder> optionsAction)
|
||||
{
|
||||
DbContextOptionsAction = optionsAction;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user