【问题标题】:MAUI dependency injection service resolve in Program.csProgram.cs 中的 MAUI 依赖注入服务解析
【发布时间】:2023-01-21 18:32:43
【问题描述】:

MAUI 的依赖注入设置类似于 ASP.NET Core 在 Startup.cs 类中的设置。这个默认设置在MauiProgram.cs文件中。

我的问题是:如何在服务注册后在此文件中获取服务实例?我想,一种解决方案如下,但如果这些服务的构造函数随时间发生变化,我也必须编辑此代码:

    var keyValueStore = new PreferencesKeyValueStore();
    var accountService = new AccountService(keyValueStore);
    var profileService = new ProfileService(keyValueStore);
    
    builder.Services.AddSingleton<IKeyValueStore>(keyValueStore);
    builder.Services.AddSingleton<IAccountService>(accountService);
    builder.Services.AddSingleton<IProfileService>(profileService);

    //Here now I can use accountService and profileService to do something

我找不到更优雅的解决方案,可以从 DI 容器为我返回服务实例。就像是:

    builder.Services.AddSingleton<IKeyValueStore, PreferencesKeyValueStore>();
    builder.Services.AddSingleton<IAccountService, AccountService>;
    builder.Services.AddSingleton<IProfileService, ProfileService>();
    
    //Now I can't perform something like: var accountService = diContainer.GetInstance<IAccountService>(); or similar.

我不知道如何到达 di 容器并要求它为我提供注册实例。

【问题讨论】:

标签: c# asp.net-core dependency-injection maui


【解决方案1】:

实际上,文档提供了一种简单的方法。 Check it here

他们建议使用 Element 类型的任何对象的 Handler 属性,您可以在其中编写代码:

// Considering you want to resolve a service from your custom interface IMyService

var service = this.Handler.MauiContext.Services.GetServices<IMyService>();

// Then you can use the resolved service..

但是有一些问题,就我个人而言,它对我来说从来没有用过,当我使用这个解决方案时,Handler属性总是null,我还没有找到任何其他解决方案..

希望对你有帮助..

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 2022-12-20
    • 2021-10-29
    • 2013-01-22
    • 1970-01-01
    • 2020-09-09
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多