var builder = new ContainerBuilder(); builder.RegisterType().As ().InstancePerLifetimeScope(); using (var container = builder.Build()) { using (var scope = container.BeginLifetimeScope()) { var service = scope.Resolve (); // Use the service... } } // MyService instance automatically disposed of
services.AddDbContextThis code uses the Microsoft.Extensions.DependencyInjection package library.(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient ); using (var scope = app.ApplicationServices.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService (); // Use the dbContext... } // MyDbContext instance automatically disposed of