如何在 Template10 中使用 Unity IoC 容器? [英] How do I use a Unity IoC container with Template10?

查看:36
本文介绍了如何在 Template10 中使用 Unity IoC 容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 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:

  1. 用户界面(通用应用)
  2. UI 逻辑(通用库)
  3. 核心逻辑(便携式库).

我有以下问题:

  1. 我应该为整个应用使用一个容器,还是为每个程序集创建一个容器?<​​/li>
  2. 我应该在哪里创建容器并注册我的服务?
  3. 各种程序集中的不同类应该如何访问容器?单例模式?

我已经阅读了很多关于 DI 和 IoC 的内容,但我需要知道如何在实践中应用所有理论,特别是在 Template10 中.

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 Container 不熟悉.

我的例子是使用 LightInject,你可以使用 Unity 应用类似的概念.要在 ViewModel 上启用 DI,您需要在项目的 App.xaml.cs 上覆盖 ResolveForPage.

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 会自动设置 DataContextMainPageViewModel,如果你想使用 {x:bind}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); }
    }
}

这篇关于如何在 Template10 中使用 Unity IoC 容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆