I have an app based on Template10 and want to handle my dependency injection using IoC. I am leaning toward using Unity for this. My app is divided into three assemblies:
I have these questions:
I have read a lot about DI and IoC but I need to know how to apply all the theory in practice, specifically in Template10.
The code to register:
// where should I put this code?
var container = new UnityContainer();
container.RegisterType<ISettingsService, RoamingSettingsService);
And then the code to retrieve the instances:
var container = ???
var settings = container.Resolve<ISettingsService>();
I not familiar with Unity Container
.
My example is using LightInject
, you can apply similar concept using Unity
.
To enable DI on ViewModel
you need to override ResolveForPage
on App.xaml.cs
on your project.
public class MainPageViewModel : ViewModelBase
{
ISettingsService _setting;
public MainPageViewModel(ISettingsService setting)
{
_setting = setting;
}
}
[Bindable]
sealed partial class App : Template10.Common.BootStrapper
{
internal static ServiceContainer Container;
public App()
{
InitializeComponent();
}
public override async Task OnInitializeAsync(IActivatedEventArgs args)
{
if(Container == null)
Container = new ServiceContainer();
Container.Register<INavigable, MainPageViewModel>(typeof(MainPage).FullName);
Container.Register<ISettingsService, RoamingSettingsService>();
// other initialization code here
await Task.CompletedTask;
}
public override INavigable ResolveForPage(Page page, NavigationService navigationService)
{
return Container.GetInstance<INavigable>(page.GetType().FullName);
}
}
Template10
will automaticaly set DataContext
to MainPageViewModel
, if you want to use {x:bind}
on MainPage.xaml.cs
:
public class MainPage : Page
{
MainPageViewModel _viewModel;
public MainPageViewModel ViewModel
{
get { return _viewModel??(_viewModel = (MainPageViewModel)this.DataContext); }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With