gpt4 book ai didi

c# - MvvmCross 语法,用于使用插件中定义的服务以及该服务在应用程序中的生命周期

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:47 26 4
gpt4 key购买 nike

我有一个 LoginService 及其在 MvvmCross (Mvx) 插件中定义的接口(interface)。

我的 Mvx 应用程序使用此插件的核心 PCL 使用 App.cs 像这样注册它:

        CreatableTypes(typeof(LoginService).GetTypeInfo().Assembly)
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();

然后它使用 CustomAppStart 类来启动应用程序以确定使用哪个 ViewModel 启动应用程序:

RegisterAppStart(new CustomAppStart(Mvx.Resolve<ILoginService>()));

CustomAppStart 定义为:

        public CustomAppStart(ILoginService loginService)
{
_loginService = loginService;
}

public void Start(object hint = null)
{
if (!_loginService.IsLoggedIn)
{
ShowViewModel<LoginViewModel>();
}
else
{
ShowViewModel<HomeViewModel>();
}
}

两部分问题:

  1. 我对 CreatableTypesRegisterAppStart 使用插件中定义的 LoginService

  2. 我知道通过使用 RegisterAsLazySingleton() 我会得到相同的结果当我请求它时登录服务实例,但是它的生命周期是多少那个例子?一旦我在 CustomAppStart 中请求它,状态那个实例只是留在内存中,供我调用和使用或当我的其中一个时,Mvx 是否神奇地保存并补充了它的状态ViewModels 在其请求中请求相同的 ILoginService 实例构造函数?

最佳答案

1. 我认为您用于 CreatableTypes 的语法没问题。

当不在 App 中使用它时,记录的语法是:

"当然,您也可以在 Core 以外的程序集上使用相同类型的注册逻辑 - 例如:

    typeof(Reusable.Helpers.MyHelper).Assembly.CreatableTypes()
.EndingWith("Helper")
.AsInterfaces()
.RegisterAsDynamic();

"来自 https://github.com/slodge/MvvmCross/wiki/Service-Location-and-Inversion-of-Control#bulk-registration-by-convention

CreateableTypes()EndingWith() 等都是作用于 System.Type 的相当短的扩展方法 - 您可以看到它们在 IoC/MvxTypeExtensions.cs - 例如

    public static IEnumerable<Type> CreatableTypes(this Assembly assembly)
{
return assembly
.ExceptionSafeGetTypes()
.Where(t => !t.IsAbstract)
.Where(t => t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Any());
}

2. 单例的生命周期是,一旦创建,只要应用程序存在,它就会一直保留在 RAM 中。从 RAM 中删除它的唯一方法是删除对它的所有引用 - 包括删除 IoC 容器引用(这只能通过在其位置注册一个新实现来完成)。

关于c# - MvvmCross 语法,用于使用插件中定义的服务以及该服务在应用程序中的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com