Microsoft included WPF support in first public release of .NET Core 3. This blog shows steps to create WPF application in .Net Core. This includes adding dependency injection and EF Core using AddDbContextPool. AddDbContextPool is quite useful when you want to run multiple instances of application in a windows server RDS connections, it re-uses DbContext connection. Real advantage of it is in dot net core web api (check blog here to configure AddDbContextPool with dot net core web api)
Create a new project:
Open command prompt and type below command:
dotnet new wpf -o NewWpfApp1
Dependency Injection: ServiceCollection class provides plumbing to configure dependency injection.
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private IServiceProvider serviceProvider = null;
private void Application_Startup(object sender, StartupEventArgs e)
{
IServiceCollection serverCollection = new ServiceCollection();
ConfigureServices(serverCollection);
if (serviceProvider == null)
throw new NullReferenceException("serviceProvider is null");
MainWindow window = new MainWindow();
window.DataContext = serviceProvider.GetService<MainViewModel>();
window.ShowDialog();
}
private void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddDbContextPool<TestDataContext>(options => options.UseSqlServer(@"Server=USER-PC\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"));
serviceCollection.AddSingleton<ITitle, ApplicationTitle>();
serviceCollection.AddTransient<MainViewModel>();
serviceProvider = serviceCollection.BuildServiceProvider();
}
}
Entity Framework Core
DataContext:
public class TestDataContext : DbContext
{
public TestDataContext(DbContextOptions options)
: base(options)
{ }
public DbSet<testModel> data { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<testModel>()
.ToTable("testtable");
modelBuilder.Entity<testModel>()
.Property(b => b.Id)
.HasColumnName("id");
}
}
Good Example: