-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
189 lines (159 loc) · 6.35 KB
/
App.xaml.cs
File metadata and controls
189 lines (159 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Windows;
using WpfApp2.Data;
using WpfApp2.Data.Repositories;
using WpfApp2.ViewModels;
using WpfApp2.ViewModels.Base;
using WpfApp2.Services;
using WpfApp2.Services.Interfaces;
namespace WpfApp2;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private IHost? _host;
protected override async void OnStartup(StartupEventArgs e)
{
try
{
// Configure and start the host
_host = CreateHostBuilder(e.Args).Build();
// Initialize database
await InitializeDatabaseAsync();
await _host.StartAsync();
// Configure Serilog
ConfigureSerilog();
// Show the main window
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
catch (Exception ex)
{
MessageBox.Show($"Application startup failed: {ex.Message}", "Startup Error",
MessageBoxButton.OK, MessageBoxImage.Error);
Shutdown();
}
}
protected override async void OnExit(ExitEventArgs e)
{
if (_host != null)
{
await _host.StopAsync();
_host.Dispose();
}
Log.CloseAndFlush();
base.OnExit(e);
}
private IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
config.SetBasePath(AppContext.BaseDirectory);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.ConfigureServices((context, services) =>
{
ConfigureServices(services, context.Configuration);
})
.ConfigureLogging((context, logging) =>
{
logging.ClearProviders();
logging.AddSerilog();
});
}
private void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
// Register configuration
services.AddSingleton(configuration);
// Register Database Context
var connectionString = configuration.GetConnectionString("DefaultConnection") ??
"Data Source=enterprise_manager.db;Cache=Shared";
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlite(connectionString);
if (configuration.GetValue<bool>("Database:EnableSensitiveDataLogging"))
{
options.EnableSensitiveDataLogging();
}
if (configuration.GetValue<bool>("Database:EnableDetailedErrors"))
{
options.EnableDetailedErrors();
}
});
// Register Unit of Work and Repositories
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IEmployeeRepository, EmployeeRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IDepartmentRepository, DepartmentRepository>();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
// Register Windows
services.AddTransient<MainWindow>();
// Register ViewModels
services.AddTransient<MainViewModel>();
services.AddTransient<DashboardViewModel>();
services.AddTransient<EmployeeViewModel>();
services.AddTransient<ProjectViewModel>();
services.AddTransient<DepartmentViewModel>();
// Register Core Services (updated to use repositories)
services.AddSingleton<IAuditService, AuditService>();
services.AddSingleton<INotificationService, NotificationService>();
// Note: These services can now be updated to use the repository pattern instead of in-memory storage
services.AddScoped<IEmployeeService, EmployeeService>();
services.AddScoped<IProjectService, ProjectService>();
services.AddScoped<IDepartmentService, DepartmentService>();
// Register AutoMapper (for mapping between entities and DTOs if needed)
// services.AddAutoMapper(typeof(App));
// Register other services
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddLogging();
// Register HTTP Client for external API calls (if needed)
services.AddHttpClient();
}
private async Task InitializeDatabaseAsync()
{
try
{
using var scope = _host!.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<App>>();
logger.LogInformation("Initializing database...");
// Ensure database is created
await context.Database.EnsureCreatedAsync();
// Apply any pending migrations
if (context.Database.GetPendingMigrations().Any())
{
logger.LogInformation("Applying pending migrations...");
await context.Database.MigrateAsync();
}
logger.LogInformation("Database initialization completed");
}
catch (Exception ex)
{
Log.Error(ex, "Failed to initialize database");
throw;
}
}
private void ConfigureSerilog()
{
var configuration = _host!.Services.GetRequiredService<IConfiguration>();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "ModernWPF Enterprise Manager")
.Enrich.WithProperty("Version", "1.0.0")
.CreateLogger();
Log.Information("Application starting up...");
}
}