xamarin 如何使用AutoFac从变量类型解析服务

mefy6pfw  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(97)

我有一个带有方法的类

public Task ServiceResolver(ILifetimeScope scope, IViewModel viewModel)
{
 Type type = viewModel.GetType();
 scope.Resolve<type>();
}

有没有可能解决类似于使用GetType或typeof()的服务,这是行不通的,但我认为如果有其他选择。
问题是我有多个viewModel,如果我想在viewModel内部使用其他已解析的viewModel,我必须引用AutoFac容器,或者在启动应用程序之前解析所有的viewModel。

fsi0uk1n

fsi0uk1n1#

您应该能够将类型直接传递给Resolve

public Task ServiceResolver(ILifetimeScope scope, IViewModel viewModel)
{
 Type type = viewModel.GetType();
 var resolvedInstance = (IViewModel)scope.Resolve(type);
}

Resolve的多载会传回object,因此您会在使用它之前先转型。

相关问题