/// <summary> /// Includes provided model creator that takes responsibility of creating model for built type /// </summary> /// <param name="modelCreator">Model creator concrete object that cannot be null</param> /// <returns></returns> public DbContextBuilder WithOnModelCreating(IDbContextModelCreator modelCreator) { if (modelCreator == null) { throw new ArgumentNullException("Model creator cannot be null"); } ModelCreator = modelCreator; return(this); }
public void CheckIfModelCreatorIsRegistered() { Mock <IDbContextModelCreator> modelCreatorMock = new Mock <IDbContextModelCreator>(); IDbContextModelCreator modelCreator = modelCreatorMock.Object; DbContextBuilder contextBuilder = new DbContextBuilder() .WithOnModelCreating(modelCreator); ServiceCollection services = new ServiceCollection(); services.AddDbContext(contextBuilder); ServiceDescriptor modelCreatorDescriptor = services .SingleOrDefault(d => d.ServiceType == typeof(IDbContextModelCreator)); Assert.NotNull(modelCreatorDescriptor); }
/// <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; }