英文:
How to re-register refit handlers in MAUI
问题
在我的 MAUI 中,我使用以下代码片段注册自定义身份验证处理程序。
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCompatibility()
.UseMauiCommunityToolkit()
.RegisterRefitClients();
return builder.Build();
}
}
而我的 RegisterRefitClients
扩展方法如下。
public static MauiAppBuilder RegisterRefitClients(this MauiAppBuilder mauiAppBuilder)
{
mauiAppBuilder.Services.AddRefitClient<IMyApiService>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.BASE_URL))
.AddHttpMessageHandler<AuthHeaderHandler>();
return mauiAppBuilder;
}
这里的关键是,Configuration.BASE_URL
可以在运行时更改。默认情况下,它总是指向我们的生产服务器。但测试人员可以在运行时将其更改为暂存/开发服务器。我想在运行时调用这个方法,以便为新更改的暂存服务器设置自定义身份验证处理程序。但一旦应用程序启动,我无法在应用程序的任何地方获取 MauiAppBuilder
实例。如何在运行时调用 RegisterRefitClients
方法呢?
英文:
In my MAUI, I register custom auth handlers using the following code snippet.
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCompatibility()
.UseMauiCommunityToolkit()
.RegisterRefitClients()
return builder.Build();
}
}
And my RegisterRefitClients extension method looks like this.
public static MauiAppBuilder RegisterRefitClients(this MauiAppBuilder mauiAppBuilder)
{
mauiAppBuilder.Services.AddRefitClient<IMyApiService>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.BASE_URL))
.AddHttpMessageHandler<AuthHeaderHandler>();
return mauiAppBuilder;
}
Here, the thing is, Configuration.BASE_URL
can change at run time. By default, it always points to our production server. But the testers can change it to staging/dev server at run time. I want to invoke this method at run time, in order to set custom auth handler for the newly changed staging server.
But I cannot get the MauiAppBuilder
instance anywhere in the app once it is initiated.
How do I call the RegisterRefitClients
at run time?
答案1
得分: 2
RegisterRefitClients不能在程序开始运行时调用。.NET MAUI允许从单一位置初始化应用程序。MauiProgram类是应用程序的入口点,用于设置配置并连接应用程序将使用的服务。一旦程序开始运行,就无法更改MauiProgram
。
英文:
RegisterRefitClients can not be called when the program start running. .NET MAUI enables apps to be initialized from a single location. The MauiProgram class is the entry point to the application, setting up configuration and wiring up services the application will use. Once the program starts, you can not change the MauiProgram
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论