Skip to content

Instantly share code, notes, and snippets.

@tonysneed
Last active December 20, 2018 23:01
Embed
What would you like to do?
DependencyResolver
public class DependencyResolver
{
public IServiceProvider ServiceProvider { get; }
public string CurrentDirectory { get; set; }
public DependencyResolver()
{
// Set up Dependency Injection
IServiceCollection services = new ServiceCollection();
ConfigureServices(services);
ServiceProvider = services.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(ProductsDbContext));
var optionsBuilder = new DbContextOptionsBuilder<ProductsDbContext>();
optionsBuilder.UseSqlServer(connectionString, builder => builder.MigrationsAssembly("EfDesignDemo.EF.Design"));
return new ProductsDbContext(optionsBuilder.Options);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment