-
-
Notifications
You must be signed in to change notification settings - Fork 23
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
Request for Adding Dependency Injection Support to dotnet-maui-templates #136
Comments
I don't understand your request. Please elaborate. |
Here is an example of using dependency injection in a MAUI app: First, in the startup class of the MAUI app, we need to create and configure a DI container. We can use the ServiceCollection class provided by the Microsoft.Extensions.DependencyInjection NuGet package:
In the above example, we register the IMyService interface as an instance of the MyService class, so we can use IMyService to retrieve an instance of MyService throughout the application. Next, we can use the service in other parts of the application. For example, we can inject the IMyService service into the page constructor, as shown below:
Now, in the code of the MyPage page, we can use the _myService instance to call methods defined in the IMyService interface. This is just a simple example, but it demonstrates how to use dependency injection in a MAUI app. By using dependency injection, we can decouple different parts of the application and write more easily testable and maintainable code. |
You can do that right now using the MauiProgram.cs source file. Register your dependencies like: builder.Services.AddTransient<IMyService, MyService>();
// Register the Page with the appropriate scope
builder.Services.AddTransient<MyPage>(); Then inject the dependency into the page as described in your code snippet. The only catch is that your page has to be resolved from the DI container so that its dependencies are auto-resolved (IMyService is a dependency for MyPage). For example: public partial class App : Application
{
public App(MyPage myPage)
{
MainPage = myPage;
}
} If you prefer the ConfigureServices approach, it's also available in my MAUI Toolkit here, add the NuGet package as a reference, and then include it in the .NET MAUI startup pipeline. var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>()
.ConfigureServices(services =>
{
// Do all the stuff with the "services" parameter
});
return builder.Build(); |
To get a glimpse of how it works, create a .NET MAUI project from the All-in-One template with the MVVM option. dotnet new mauiapp -o MvvmApp -mvvm The ViewModel is injected as a dependency and resolved from the DI container. |
A more detailed sample: dotnet new mauiapp -o NavApp -dp Hierarchical -mvvm |
Since this is covered in the de facto implementation of .NET MAUI, closing this issue. |
No description provided.
The text was updated successfully, but these errors were encountered: