autofac dependency injection in .net maui



I am working on migrating xamarin forms application to .net MAUI application.

In xamarin froms application i am using autofac dependency injection.

can we use autofac dependency injection in .net MAUI.

if YES how to re use that code?

A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,207 questions
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 29,206 Reputation points Microsoft Vendor


    In Xamarin.Forms, you can use autofac as a dependency injection container, which provides the IContainer and ContainerBuilder types. Please See Dependency resolution in Xamarin.Forms - Xamarin | Microsoft Learn and Dependency Injection - Xamarin | Microsoft Learn.

    In MAUI, you can register dependencies in MauiProgram.cs. The MauiProgram class will call into the CreateMauiApp method to create a MauiAppBuilder object. The MauiAppBuilder object has a Services property of type IServiceCollection, which provides a place to register our components, such as views, view models, and services for dependency injection. Any components registered with the Services property will be provided to the dependency injection container when the MauiAppBuilder.Build method is called.

    For more details, you can refer to Dependency Injection | Microsoft Learn.

    (There is an official sample that covers this functionality, you can see the source code:services.AddSingleton<HomeViewModel>(); )

    Best Regards,

    Wenyan Zhang

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful