How to inject .net core EF into WPF application












1















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










share|improve this question

























  • Possible duplicate of Where is the composition root in a WPF MDI application?

    – Crowcoder
    Nov 24 '18 at 15:13











  • Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

    – Nkosi
    Nov 24 '18 at 15:16











  • Remove the constructor with the options

    – Nkosi
    Nov 24 '18 at 15:19











  • @Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

    – Bassie
    Nov 24 '18 at 15:22











  • @Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

    – Nkosi
    Nov 24 '18 at 15:25


















1















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










share|improve this question

























  • Possible duplicate of Where is the composition root in a WPF MDI application?

    – Crowcoder
    Nov 24 '18 at 15:13











  • Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

    – Nkosi
    Nov 24 '18 at 15:16











  • Remove the constructor with the options

    – Nkosi
    Nov 24 '18 at 15:19











  • @Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

    – Bassie
    Nov 24 '18 at 15:22











  • @Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

    – Nkosi
    Nov 24 '18 at 15:25
















1












1








1


1






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










share|improve this question
















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







c# wpf entity-framework-core .net-standard






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 15:29







Bassie

















asked Nov 24 '18 at 15:07









BassieBassie

3,8921949




3,8921949













  • Possible duplicate of Where is the composition root in a WPF MDI application?

    – Crowcoder
    Nov 24 '18 at 15:13











  • Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

    – Nkosi
    Nov 24 '18 at 15:16











  • Remove the constructor with the options

    – Nkosi
    Nov 24 '18 at 15:19











  • @Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

    – Bassie
    Nov 24 '18 at 15:22











  • @Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

    – Nkosi
    Nov 24 '18 at 15:25





















  • Possible duplicate of Where is the composition root in a WPF MDI application?

    – Crowcoder
    Nov 24 '18 at 15:13











  • Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

    – Nkosi
    Nov 24 '18 at 15:16











  • Remove the constructor with the options

    – Nkosi
    Nov 24 '18 at 15:19











  • @Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

    – Bassie
    Nov 24 '18 at 15:22











  • @Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

    – Nkosi
    Nov 24 '18 at 15:25



















Possible duplicate of Where is the composition root in a WPF MDI application?

– Crowcoder
Nov 24 '18 at 15:13





Possible duplicate of Where is the composition root in a WPF MDI application?

– Crowcoder
Nov 24 '18 at 15:13













Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

– Nkosi
Nov 24 '18 at 15:16





Did you properly configure the ApplicationDbContext with the container. It would appear you did not setup the context builder options for the DbContext

– Nkosi
Nov 24 '18 at 15:16













Remove the constructor with the options

– Nkosi
Nov 24 '18 at 15:19





Remove the constructor with the options

– Nkosi
Nov 24 '18 at 15:19













@Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

– Bassie
Nov 24 '18 at 15:22





@Nkosi That seems to have got rid of the error! However, in MainWindow I can see that Db is null

– Bassie
Nov 24 '18 at 15:22













@Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

– Nkosi
Nov 24 '18 at 15:25







@Bassie that depends on when you are checking its value. If you check it before the container has had a chance to inject the dependency, like having a breakpoint in the constructor, it will definitely be null at that point in the initialization process

– Nkosi
Nov 24 '18 at 15:25














1 Answer
1






active

oldest

votes


















4














The original error was because the container was selecting the constructor that expected DbContextOptionsBuilder which the conateinr did not know how to resolve properly.



Since the context is being configured within the OnConfiguring override then there is no need for



public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }


Remove that constructor so the container resolve the context without errors.



Depending on the flow of dependency initialization and access to it, that context should really be explicitly injected into a view model and not directly on the View.



Following MVVM, have all the necessary dependencies and bindable properties in the view model



public class MainWindowViewModel : BaseViewModel {
private readonly ApplicationDbContext db;

public MainWindowViewModel(ApplicationDbContext db) {
this.db = db;
}

private ICommand goPack;
public ICommand GoPack {
get {
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
}


Update the View to depend on the view model



public class MainWindow : Window {
[Dependency]
public MainWindowViewModel ViewModel {
set { DataContext = value; }
}

public MainWindow() {
InitializeComponent();
Loaded += OnLoaded;
}

void OnLoaded(object sender, EventArgs args) {
FrameContent.Navigate(new PageConsignments());
}
}


All that is left now is to make sure all dependencies are registered with container



public class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<MainWindowViewModel>();
container.RegisterType<MainWindow>();

MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}


Where ever possible, The Explicit Dependencies Principle via constructor injection should be preferred over property injection.



But since most views do not lend well to constructor injection the latter is usually applied. By making sure the view model has all the necessary dependencies before injecting it into the view you ensure that all required values are available when needed.






share|improve this answer


























  • This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

    – Bassie
    Nov 24 '18 at 16:27











  • That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

    – Nkosi
    Nov 24 '18 at 16:36













  • @Nkosi With this approach, do I need to explicitly Dispose the DbContext?

    – Paolo Go
    Feb 13 at 2:34











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459473%2fhow-to-inject-net-core-ef-into-wpf-application%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














The original error was because the container was selecting the constructor that expected DbContextOptionsBuilder which the conateinr did not know how to resolve properly.



Since the context is being configured within the OnConfiguring override then there is no need for



public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }


Remove that constructor so the container resolve the context without errors.



Depending on the flow of dependency initialization and access to it, that context should really be explicitly injected into a view model and not directly on the View.



Following MVVM, have all the necessary dependencies and bindable properties in the view model



public class MainWindowViewModel : BaseViewModel {
private readonly ApplicationDbContext db;

public MainWindowViewModel(ApplicationDbContext db) {
this.db = db;
}

private ICommand goPack;
public ICommand GoPack {
get {
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
}


Update the View to depend on the view model



public class MainWindow : Window {
[Dependency]
public MainWindowViewModel ViewModel {
set { DataContext = value; }
}

public MainWindow() {
InitializeComponent();
Loaded += OnLoaded;
}

void OnLoaded(object sender, EventArgs args) {
FrameContent.Navigate(new PageConsignments());
}
}


All that is left now is to make sure all dependencies are registered with container



public class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<MainWindowViewModel>();
container.RegisterType<MainWindow>();

MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}


Where ever possible, The Explicit Dependencies Principle via constructor injection should be preferred over property injection.



But since most views do not lend well to constructor injection the latter is usually applied. By making sure the view model has all the necessary dependencies before injecting it into the view you ensure that all required values are available when needed.






share|improve this answer


























  • This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

    – Bassie
    Nov 24 '18 at 16:27











  • That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

    – Nkosi
    Nov 24 '18 at 16:36













  • @Nkosi With this approach, do I need to explicitly Dispose the DbContext?

    – Paolo Go
    Feb 13 at 2:34
















4














The original error was because the container was selecting the constructor that expected DbContextOptionsBuilder which the conateinr did not know how to resolve properly.



Since the context is being configured within the OnConfiguring override then there is no need for



public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }


Remove that constructor so the container resolve the context without errors.



Depending on the flow of dependency initialization and access to it, that context should really be explicitly injected into a view model and not directly on the View.



Following MVVM, have all the necessary dependencies and bindable properties in the view model



public class MainWindowViewModel : BaseViewModel {
private readonly ApplicationDbContext db;

public MainWindowViewModel(ApplicationDbContext db) {
this.db = db;
}

private ICommand goPack;
public ICommand GoPack {
get {
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
}


Update the View to depend on the view model



public class MainWindow : Window {
[Dependency]
public MainWindowViewModel ViewModel {
set { DataContext = value; }
}

public MainWindow() {
InitializeComponent();
Loaded += OnLoaded;
}

void OnLoaded(object sender, EventArgs args) {
FrameContent.Navigate(new PageConsignments());
}
}


All that is left now is to make sure all dependencies are registered with container



public class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<MainWindowViewModel>();
container.RegisterType<MainWindow>();

MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}


Where ever possible, The Explicit Dependencies Principle via constructor injection should be preferred over property injection.



But since most views do not lend well to constructor injection the latter is usually applied. By making sure the view model has all the necessary dependencies before injecting it into the view you ensure that all required values are available when needed.






share|improve this answer


























  • This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

    – Bassie
    Nov 24 '18 at 16:27











  • That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

    – Nkosi
    Nov 24 '18 at 16:36













  • @Nkosi With this approach, do I need to explicitly Dispose the DbContext?

    – Paolo Go
    Feb 13 at 2:34














4












4








4







The original error was because the container was selecting the constructor that expected DbContextOptionsBuilder which the conateinr did not know how to resolve properly.



Since the context is being configured within the OnConfiguring override then there is no need for



public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }


Remove that constructor so the container resolve the context without errors.



Depending on the flow of dependency initialization and access to it, that context should really be explicitly injected into a view model and not directly on the View.



Following MVVM, have all the necessary dependencies and bindable properties in the view model



public class MainWindowViewModel : BaseViewModel {
private readonly ApplicationDbContext db;

public MainWindowViewModel(ApplicationDbContext db) {
this.db = db;
}

private ICommand goPack;
public ICommand GoPack {
get {
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
}


Update the View to depend on the view model



public class MainWindow : Window {
[Dependency]
public MainWindowViewModel ViewModel {
set { DataContext = value; }
}

public MainWindow() {
InitializeComponent();
Loaded += OnLoaded;
}

void OnLoaded(object sender, EventArgs args) {
FrameContent.Navigate(new PageConsignments());
}
}


All that is left now is to make sure all dependencies are registered with container



public class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<MainWindowViewModel>();
container.RegisterType<MainWindow>();

MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}


Where ever possible, The Explicit Dependencies Principle via constructor injection should be preferred over property injection.



But since most views do not lend well to constructor injection the latter is usually applied. By making sure the view model has all the necessary dependencies before injecting it into the view you ensure that all required values are available when needed.






share|improve this answer















The original error was because the container was selecting the constructor that expected DbContextOptionsBuilder which the conateinr did not know how to resolve properly.



Since the context is being configured within the OnConfiguring override then there is no need for



public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }


Remove that constructor so the container resolve the context without errors.



Depending on the flow of dependency initialization and access to it, that context should really be explicitly injected into a view model and not directly on the View.



Following MVVM, have all the necessary dependencies and bindable properties in the view model



public class MainWindowViewModel : BaseViewModel {
private readonly ApplicationDbContext db;

public MainWindowViewModel(ApplicationDbContext db) {
this.db = db;
}

private ICommand goPack;
public ICommand GoPack {
get {
return goPack
?? (goPack = new ActionCommand(() =>
{
var c = db.Parts;
FrameContent.Navigate(new PageConsignments());
}));
}
}
}


Update the View to depend on the view model



public class MainWindow : Window {
[Dependency]
public MainWindowViewModel ViewModel {
set { DataContext = value; }
}

public MainWindow() {
InitializeComponent();
Loaded += OnLoaded;
}

void OnLoaded(object sender, EventArgs args) {
FrameContent.Navigate(new PageConsignments());
}
}


All that is left now is to make sure all dependencies are registered with container



public class App : Application {
protected override void OnStartup(StartupEventArgs e) {
IUnityContainer container = new UnityContainer();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<MainWindowViewModel>();
container.RegisterType<MainWindow>();

MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}


Where ever possible, The Explicit Dependencies Principle via constructor injection should be preferred over property injection.



But since most views do not lend well to constructor injection the latter is usually applied. By making sure the view model has all the necessary dependencies before injecting it into the view you ensure that all required values are available when needed.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 24 '18 at 15:55

























answered Nov 24 '18 at 15:46









NkosiNkosi

115k16128193




115k16128193













  • This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

    – Bassie
    Nov 24 '18 at 16:27











  • That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

    – Nkosi
    Nov 24 '18 at 16:36













  • @Nkosi With this approach, do I need to explicitly Dispose the DbContext?

    – Paolo Go
    Feb 13 at 2:34



















  • This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

    – Bassie
    Nov 24 '18 at 16:27











  • That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

    – Nkosi
    Nov 24 '18 at 16:36













  • @Nkosi With this approach, do I need to explicitly Dispose the DbContext?

    – Paolo Go
    Feb 13 at 2:34

















This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

– Bassie
Nov 24 '18 at 16:27





This works for MainWindow but when trying to display other pages in that window they don't have the requied dependencies

– Bassie
Nov 24 '18 at 16:27













That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

– Nkosi
Nov 24 '18 at 16:36







That is just a matter of design choices. You can just as easily inject the necessary pages and pass them forward.

– Nkosi
Nov 24 '18 at 16:36















@Nkosi With this approach, do I need to explicitly Dispose the DbContext?

– Paolo Go
Feb 13 at 2:34





@Nkosi With this approach, do I need to explicitly Dispose the DbContext?

– Paolo Go
Feb 13 at 2:34




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459473%2fhow-to-inject-net-core-ef-into-wpf-application%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'