Created
December 21, 2018 20:36
-
-
Save tonysneed/48e9efe43f6b78325566c343a077d719 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DependencyResolver | |
{ | |
public IServiceProvider ServiceProvider { get; } | |
public string CurrentDirectory { get; set; } | |
public Action<IServiceCollection> RegisterServices { get; } | |
public DependencyResolver(Action<IServiceCollection> registerServices = null) | |
{ | |
// Set up Dependency Injection | |
var serviceCollection = new ServiceCollection(); | |
RegisterServices = registerServices; | |
ConfigureServices(serviceCollection); | |
ServiceProvider = serviceCollection.BuildServiceProvider(); | |
} | |
private void ConfigureServices(IServiceCollection services) | |
{ | |
// Register env and config services | |
services.AddTransient<IEnvironmentService, EnvironmentService>(); | |
services.AddTransient<IConfigurationService, ConfigurationService> | |
(provider => new ConfigurationService(provider.GetService<IEnvironmentService>()) | |
{ | |
CurrentDirectory = CurrentDirectory | |
}); | |
// Register DbContext class | |
services.AddTransient(provider => | |
{ | |
var configService = provider.GetService<IConfigurationService>(); | |
var connectionString = configService.GetConfiguration().GetConnectionString(nameof(SampleDbContext)); | |
var optionsBuilder = new DbContextOptionsBuilder<SampleDbContext>(); | |
optionsBuilder.UseSqlServer(connectionString, builder => builder.MigrationsAssembly("NetCoreLambda.EF.Design")); | |
return new SampleDbContext(optionsBuilder.Options); | |
}); | |
// Register other services | |
RegisterServices?.Invoke(services); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment