Best place to put initialization code. #20353
-
Where is the best place to put initialization code to run it only once. Currently we had it on the Now with .net8 what is the correct and best place to initialize our code which only runs the first time irrespective of navigating to or away from the page |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
MauiProgram.cs |
Beta Was this translation helpful? Give feedback.
-
I remember reading someone's comment somewhere in this repo that you can use the Handler lifecycle for one-time "setup/teardown" methods. I don't remember where I saw it though. This is what I use: Create an extension so it's kept clean: public static class HandlerChangingEventArgsExtension
{
public static bool AttachingToHandler(this HandlerChangingEventArgs args)
{
return args.NewHandler != null && args.OldHandler == null;
}
public static bool DetachingFromHandler(this HandlerChangingEventArgs args)
{
return args.NewHandler == null && args.OldHandler != null;
}
} Create some base class for the Pages you use and override protected override void OnHandlerChanging(HandlerChangingEventArgs args)
{
base.OnHandlerChanging(args);
if (args.AttachingToHandler())
Creating();
else if (args.DetachingFromHandler())
Destroying();
}
protected virtual void Creating() { }
protected virtual void Destroying() { } You can do whatever works for you with the Creating/Destroying methods. |
Beta Was this translation helpful? Give feedback.
I remember reading someone's comment somewhere in this repo that you can use the Handler lifecycle for one-time "setup/teardown" methods. I don't remember where I saw it though.
This is what I use:
Create an extension so it's kept clean:
Create some base class for the Pages you use and override
OnHandlerChanging
:protected