在Prism中,在构造函数之前调用RegisterTypes [英] In Prism, RegisterTypes is called before constructor
问题描述
在MainActivity.cs
和AppDelegate.cs
中,我像这样初始化Configuration
对象:
In MainActivity.cs
and AppDelegate.cs
I initialize the Configuration
object like so:
LoadApplication(new App(Configuration.GetConfiguration, new AndroidInitializer()));
我将该对象插入App
类的构造函数中.
I insert that object in the constructor of the App
class.
我想在RegisterTypes
方法中注册相同的对象.
I want to register that same object in the RegisterTypes
method.
public partial class App : PrismApplication
{
public App(IConfiguration configuration, IPlatformInitializer initializer = null) : base(initializer)
{
Configuration = configuration;
}
private IConfiguration Configuration { get; }
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// Here Configuration is null.
containerRegistry.RegisterInstance<IConfiguration>(Configuration);
// Need to access configuration again.
var restClient = new RestClient(Configuration.BaseApiUrl);
containerRegistry.RegisterInstance<IRestClient>(restClient);
}
}
在RegisterTypes
方法中,Configuration
为空,因为它在构造方法之前被调用.
Within RegisterTypes
method, Configuration
is null because it is called before constructor.
有任何解决方法吗?
推荐答案
有两种方法可以完成所需的工作,具体取决于您要使用IConfiguration
完成的任务:
there are two ways to do what you need depending on exactly what it is that you're trying to accomplish with IConfiguration
:
如果您要做的只是注册IConfiguration
的实例,那么您应该在IPlatformInitializer中注册它,而不是在您的应用程序中注册.例如,您可能有:
If all you're doing is registering the instance of IConfiguration
then you should be registering it in IPlatformInitializer and not in your app. For example you might have:
public class iOSInitializer : IPlatformInitalizer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistery.RegisterInstance<IConfiguration>(new iOSConfiguration());
}
}
如果您需要专门访问有关IConfiguration
的内容,则可以遵循第一种模式并解决它来完成您需要做的事情...否则,您可以执行以下操作:
If you need to specifically access something about IConfiguration
and you could follow the first pattern and just resolve it to do what you need to do... otherwise you could do something like:
public class iOSInitializer : IPlatformInitalizer, IConfiguration
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistery.RegisterInstance<IConfiguration>(this);
}
}
然后在您的应用中,您只需执行以下操作即可:
Then in your app you could simply do:
var configuration = (IConfiguration)PlatformInitializer
这篇关于在Prism中,在构造函数之前调用RegisterTypes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!