/// <summary> /// Includes provided options creator that takes responsibility of configuring built type /// </summary> /// <param name="optionsCreator">Options creator concrete object that cannot be null</param> /// <returns></returns> public DbContextBuilder WithOnConfiguring(IDbContextOptionsCreator optionsCreator) { if (optionsCreator == null) { throw new ArgumentNullException("Options creator cannot be null"); } OptionsCreator = optionsCreator; return(this); }
public void CheckIfOptionsCreatorIsRegistered() { Mock <IDbContextOptionsCreator> optionsCreatorMock = new Mock <IDbContextOptionsCreator>(); IDbContextOptionsCreator optionsCreator = optionsCreatorMock.Object; DbContextBuilder contextBuilder = new DbContextBuilder() .WithOnConfiguring(optionsCreator); ServiceCollection services = new ServiceCollection(); services.AddDbContext(contextBuilder); ServiceDescriptor optionsCreatorDescriptor = services .SingleOrDefault(d => d.ServiceType == typeof(IDbContextOptionsCreator)); Assert.NotNull(optionsCreatorDescriptor); }
/// <summary> /// Extensions method that enables registering DbContext based on provided builder /// </summary> /// <param name="services"></param> /// <param name="contextBuilder">DbContext subtype builder that cannot be null</param> public static void AddDbContext(this IServiceCollection services, DbContextBuilder contextBuilder) { if (contextBuilder == null) { throw new ArgumentNullException("Context builder cannot be null"); } IDbContextOptionsCreator optionsCreator = contextBuilder.OptionsCreator ?? new DelegatedDbContextOptionsCreator(_ => {}); IDbContextModelCreator modelCreator = contextBuilder.ModelCreator ?? new DelegatedDbContextModelCreator(_ => {}); Type dbContextType = contextBuilder.Build(); services.AddSingleton(typeof(IDbContextOptionsCreator), optionsCreator); services.AddSingleton(typeof(IDbContextModelCreator), modelCreator); services.AddScoped(typeof(DbContext), dbContextType); }
public ConfigurableDbContext(IDbContextOptionsCreator optionsCreator, IDbContextModelCreator modelCreator) { OptionsCreator = optionsCreator; ModelCreator = modelCreator; }