Skip to content

Instantly share code, notes, and snippets.

@tonysneed
Created December 21, 2018 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonysneed/48e9efe43f6b78325566c343a077d719 to your computer and use it in GitHub Desktop.
Save tonysneed/48e9efe43f6b78325566c343a077d719 to your computer and use it in GitHub Desktop.
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