如何将Unity IoC容器与Template10一起使用? [英] How do I use a Unity IoC container with Template10?
问题描述
我有一个基于Template10的应用程序,想使用IoC处理依赖项注入。我倾向于为此使用Unity。我的应用程序分为三个程序集:
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:
- UI(通用应用程序)
- UI Logic(通用)库)
- 核心逻辑(便携式库)。
我有以下问题:
- 我应该为整个应用使用单个容器还是为每个程序集创建一个容器?</ li>
- 在哪里我应该创建一个容器并注册我的服务吗?
- 各个程序集中的不同类应该如何访问该容器?单例模式?
我已经阅读了很多有关DI和IoC的文章,但是我需要知道如何在实践中运用所有理论
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.
要注册的代码:
// 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>();
推荐答案
我对 Unity不熟悉容器
。
我的示例使用的是 LightInject
,您可以使用 Unity
。
要在 ViewModel
上启用DI,您需要覆盖 App.xaml上的
在您的项目上。 ResolveForPage
.cs
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 $ c如果要使用
{x,$ c>将自动将
: DataContext
设置为 MainPageViewModel
。 MainPage.xaml.cs
上的绑定}
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); }
}
}
这篇关于如何将Unity IoC容器与Template10一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!