Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WinUI feature: Navigation with dependency injection #4732

Open
1 of 3 tasks
gabor-budai opened this issue Apr 5, 2024 · 4 comments
Open
1 of 3 tasks

WinUI feature: Navigation with dependency injection #4732

gabor-budai opened this issue Apr 5, 2024 · 4 comments

Comments

@gabor-budai
Copy link

Is your feature request related to a problem? Please describe.

No response

Describe the solution you'd like

The generated ConfigureServices() in App.xaml.cs can be misleading, since it registers pages as services. When NavigationService.NavigateTo() is called, a type is passed to _frame.Navigate() instead of an instance. As I have seen WinUI’s API does not support passing instance to the Frame.Navigate() method. (it also makes parametrized constructors prohibited)

I found a solution to enable Frame.Navigate() to instantiate a page via an IServiceProvider interface. When Frame.Navigate() is called, it retrieves an IXamlType from the App, IXamlType.ActivateInstance() method is responsible for creating the instance from a type. The ActivateInstance() method can be redirected, and I created a sample app that shows how this redirection is implemented.
I think it would be great that the App.DI.cs could be included in the TemplateStudio’s source generator.

Describe alternatives you've considered

No response

Additional context

Here is my example app.

Applies to the following platforms:

  • WinUI
  • WPF
  • UWP
@adstep
Copy link

adstep commented Aug 10, 2024

This would be awesome to have! Was looking to see how to use DI during navigation to instantiate pages myself.

@gabor-budai
Copy link
Author

gabor-budai commented Aug 18, 2024

I made a source generator nuget.

@weitzhandler
Copy link

weitzhandler commented Dec 11, 2024

Hi @gabor-budai thanks for opening this issue, and thanks for posting the solution, can you please add a license to your repo (ideally MIT)?

@weitzhandler
Copy link

Oh I can see this one is under MIT. THANK YOU 💖

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants