Created
October 26, 2023 14:09
-
-
Save adamstirtan/68d2a8fc8871d1d76022acf70e47c369 to your computer and use it in GitHub Desktop.
.NET Console app using dependency injection and EF Core
This file contains hidden or 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
| using System; | |
| using Microsoft.EntityFrameworkCore; | |
| using Microsoft.Extensions.Configuration; | |
| using Microsoft.Extensions.DependencyInjection | |
| namespace MyApp | |
| { | |
| internal class Program | |
| { | |
| private static void Main(string[] args) | |
| { | |
| var services = CreateServices(); | |
| MyDbContext context = services.GetRequiredService<MyDbContext>(); | |
| context.Database.Migrate(); | |
| Application app = services.GetRequiredService<Application>(); | |
| app.MyLogic(); | |
| } | |
| private static ServiceProvider CreateServices() | |
| { | |
| var configuration = new ConfigurationBuilder() | |
| .AddUserSecrets(Assembly.GetExecutingAssembly()) | |
| .Build(); | |
| string connectionString = configuration.GetConnectionString("MyApp"); | |
| var serviceProvider = new ServiceCollection() | |
| .AddDbContext<MyDbContext>(options => | |
| { | |
| options.UseSqlite(connectionString); | |
| }) | |
| .AddSingleton<Application>(new Application()) | |
| .BuildServiceProvider(); | |
| return serviceProvider; | |
| } | |
| } | |
| public class Application | |
| { | |
| public void MyLogic() | |
| { | |
| // Do something epic | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment