Reputation: 1459
I am using Autofac dependecy injection in my xamarin forms project. I created a constructor and its viewmodel. And then register it in a container of Autofac. Its working fine at first. But when user comes on the page it shows the same values that I saved last time in properties. I want to reinitialize the object of viewmodel. Here is my code :
Interface:
public ILoadViewModel : INotifyPropertyChanged
{
}
ViewModel:
public class LoadViewModel : ViewModelBase, ILoadViewModel
{
private INavigationService navigationService;
public string Username { get ; set ; }
public LoadRouteViewModel(INavigationService navigationService)
{
this.navigationService = navigationService;
}
Xaml.cs :
viewModel = AppContainer.Container.Resolve<ILoadViewModel>();
At first it initialize the viewmodel. But when I open the page next time . It shows the same Username value that I stored last time.
How I can reinitailize it.
Upvotes: 0
Views: 597
Reputation: 12179
Depends on how the ViewModel
is registered with Autofac
you may experience different outcome. If you defined the scope to be SingleInstance()
(single instance scope) then the container will resolve the same instance on every Resolve
. If your intent is to get a new instance on each Resolve
(per dependency scope), you should not define any lifetime scope, so simply remove the .SingleInstance()
:
builder.RegisterType<LoadRouteViewModel>().As<ILoadRouteViewModel>();
You can read more about lifetime scopes here.
P.S.: Beside that, it is a good practice to mark the injected instances as readonly
.
Upvotes: 2