I would like to inject my .NET Core EntityFramework DbContext
(sitting in a .net standard library) into my WPF app.
I tried this Unity approach:
OnStartup
var container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
var mainWindow = container.Resolve<MainWindow>();
base.OnStartup(e);
MainWindow
private ApplicationDbContext _db;
[Dependency]
public ApplicationDbContext Db
{
get
{
return _db;
}
set
{
_db = value;
}
}
public MainWindow()
{
//StandardDatabase.Commands.Test();
InitializeComponent();
DataContext = this;
FrameContent.Navigate(new PageConsignments());
}
But I get this error at container.Resolve<MainWindow>()
:
The current type, System.Collections.Generic.IReadOnlyDictionary`2[System.Type,Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsExtension], is an interface and cannot be constructed. Are you missing a type mapping?
Does anyone know if I'm doing something wrong? Any suggestions on a better way of doing this are welcome
ApplicationDbContext
public ApplicationDbContext() : base() { }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer("Server=L-TO-THE-APTOP\\SQLEXPRESS;Database=Maloli;Trusted_Connection=True;MultipleActiveResultSets=true");
optionsBuilder.ConfigureWarnings(x => x.Ignore(CoreEventId.LazyLoadOnDisposedContextWarning));
}
As per Nkosi's suggestion, I removed the ApplicationDbContext(options)
ctor from the context, and that got rid of the error.However I am now checking the value of Db
here in MainWindow
:
private ICommand goPack;
public ICommand GoPack
{
get
{
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = _db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
But it returns null
ApplicationDbContext
with the container. It would appear you did not setup the context builder options for the DbContext – Nkosi Nov 24 '18 at 15:16MainWindow
I can see thatDb
isnull
– Bassie Nov 24 '18 at 15:22