【问题标题】:In ReactiveUI, how to call GetService for MutableDependencyResolver在 ReactiveUI 中,如何为 MutableDependencyResolver 调用 GetService
【发布时间】:2021-09-08 02:35:54
【问题描述】:

我正在阅读 You, I and ReactiveUI 这本书,我的问题与本书的源代码有关,地址为 https://github.com/kentcb/YouIandReactiveUI。自代码发布以来,ReactiveUI 和 Splat 的版本发生了变化,其中一部分代码在当前版本中无法复制。我已经联系了作者,并且在发布此问题时仍在等待回复,因此我在此处提交此问题。

在 App.xaml.cs 中有一个对 Registrations.cs 类的调用,该类传递了当前的可变依赖解析器:

public App()
{
    this.autoSuspendHelper = new AutoSuspendHelper(this);
    Registrations.Register(Splat.Locator.CurrentMutable);
}

在 Registrations.cs 类中,有一行使用 IMutableDependencyResolver 并调用 GetService:

public static void Register(IMutableDependencyResolver container)
{
    ...

    var defaultViewLocator = container.GetService<IViewLocator>();

    ...
}

我也想获得 IVewLocator 服务,但 IMutableDependencyResolver 不再有 GetService 方法。

所以我的问题是,应该如何修改这段代码以具有相同的功能?

Splat.Locator.Current 是一个 IReadonlyDependenyResolver,它有一个 GetService 方法。应该改用那个吗?我不确定是否应该更改为使用 Splat.Locator.Current 以防有使用 Splat.Locator.CurrentMutable 的原因,并想确保如果我更改为使用 Splat.Locator.Current 它不会引入任何意想不到的东西。

更新:

只是想补充一点,根据 DPVreony 的回答中的知识,它通常是实现这两个接口的同一个类,我能够在我需要的 Registrations.cs 类中实现一些后面的行。

因此,在该类中,还有一些行注册了常量。这些需要可变依赖解析器。因此,您可以将只读和可变都传递给 Registrations 类,并在需要时使用它们,如下所示:

public static void Register(IReadonlyDependencyResolver container, IMutableDependencyResolver mutableContainer)
{

    ...

    var defaultViewLocator = container.GetService<IViewLocator>();

    ...

    mutableContainer.RegisterConstant(viewLocator, typeof(IViewLocator));

    ...

    var defaultActivationForViewFetcher = container.GetService<IActivationForViewFetcher>();
       
    ...
        
    mutableContainer.RegisterConstant(activationForViewFetcher, typeof(IActivationForViewFetcher));
    mutableContainer.RegisterConstant(activationForViewFetcher, typeof(IForcibleActivationForViewFetcher));
}

然后像这样调用方法:

Registrations.Register(Splat.Locator.Current, Splat.Locator.CurrentMutable);

【问题讨论】:

    标签: c# xamarin.forms reactiveui splat


    【解决方案1】:

    由于某些 DI 容器在注册服务时的行为方式(即它们不断重新初始化),Splat 发生了变化。因此,get 功能被拆分到由 Splat.Locator.Current 公开的 IReadonlyDependenyResolver 上

    这是为了鼓励使用 MutableLocator 的心态来完成所有工作,然后你应该只需要使用 Splat.Locator.Current 进行阅读,这样你就可以使用它了。通常它是实现这 2 个接口的同一个类,因此这是一种语义更改,以减少错误地拆除定位器的风险。

    所以简而言之,Splat.Locator.Current 是用于 GetService

    希望一切都有意义。

    【讨论】:

    • 是的,这是有道理的,非常感谢您的详细解释。
    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多