首页 > 解决方案 > 如何将我从 DI 容器获取的参数从默认的空构造函数传递到基类?

问题描述

我正在使用依赖注入,我想打开一个这样的页面:

public class AppManagementPage : HeadingPageBase<AppManagementPageViewModel>
{
    public AppManagementPage(
        IMainThread mainThread,
        IAnalyticsService analyticsService,
        AppManagementPageViewModel appManagementPageViewModel) : base(appManagementPageViewModel, analyticsService, mainThread)
    {

但是我有一个问题,就是我正在使用的导航服务(Xamarin Forms Shell),除了使用默认的空构造函数打开一个页面之外,没有其他方法可以做。

所以我希望能够以另一种方式做到这一点。到目前为止,我能想到的唯一方法就是这个。但是,这不起作用,我认为我走错了路,因为它告诉我“在这种情况下使用 base 无效”。

有人可以向我建议我在这里做错了什么:

public class AppManagementPage : HeadingPageBase<AppManagementPageViewModel>
{
    public AppManagementPage()
    {
        var mainThread = Startup.ServiceProvider.GetRequiredService<IMainThread>();
        var analyticsService = Startup.ServiceProvider.GetRequiredService<IAnalyticsService>();
        var appManagementPageViewModel = Startup.ServiceProvider.GetRequiredService<AppManagementPageViewModel>();
        base(appManagementPageViewModel, analyticsService, mainThread);

如何使用默认的空构造函数调用页面,然后以正确的方式将所需的参数传递给 base?

注意我查看了其他一些帖子,在这种特殊情况下它们似乎对我没有帮助:

我可以将参数从派生类的默认构造函数传递给基构造函数吗?

标签: c#xamarin

解决方案


您可能应该使用“属性注入”。它可用于“StructureMap”和“NInject”库,例如(https://structuremap.github.io/setter-injection/ & https://github.com/ninject/Ninject/wiki/Injection-Patterns)。不幸的是,内置的依赖容器不支持这种方法。


推荐阅读