I tried to implement connection to database using Entity Framework and Dependency Injection.
I want to create Host in App.xaml.cs.
public partial class App : Application
{
public static IHost? AppHost { get; private set; }
public App()
{
AppHost = Host.CreateDefaultBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<LoginWindow>();
services.AddSingleton<LoginViewModel>();
services.AddDbContext<KnitterNotebookContext>(
options =>
{
string appSettingsPath = Path.Combine(ProjectDirectory.ProjectDirectoryFullPath, "appsettings.json");
string appSettingsString = File.ReadAllText(appSettingsPath);
AppSettings AppSettings = JsonConvert.DeserializeObject<AppSettings>(appSettingsString)!;
options.UseSqlServer(AppSettings.KnitterNotebookConnectionString);
});
})
.Build();
}
protected override async void OnStartup(StartupEventArgs e)
{
await AppHost!.StartAsync();
var startupWindow = AppHost.Services.GetRequiredService<LoginWindow>();
startupWindow.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
await AppHost!.StopAsync();
base.OnExit(e);
}
I want to pass DbContext as parameter to ViewModel, but when I do, it throws exception.
public class LoginViewModel : BaseViewModel
{
public LoginViewModel(KnitterNotebookContext knitterNotebookContext)
//public LoginViewModel()
{
KnitterNotebookContext = knitterNotebookContext;
ShowRegistrationWindowCommand = new RelayCommand(ShowRegisterWindow);
LogInCommandAsync = new AsyncRelayCommand(LogIn);
}
private KnitterNotebookContext KnitterNotebookContext { get; set; }
}
There is no problem if I use parameterless constructor of LoginViewModel and create new instances of KnitterNotebookContext with new(), but I want to pass it as a parameter. How to solve it?

