如何将Unity IoC容器与Template10一起使用? [英] How do I use a Unity IoC container with Template10?

查看:85
本文介绍了如何将Unity IoC容器与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:


  1. UI(通用应用程序)

  2. UI Logic(通用)库)

  3. 核心逻辑(便携式库)。

我有以下问题:


  1. 我应该为整个应用使用单个容器还是为每个程序集创建一个容器?<​​/ li>
  2. 在哪里我应该创建一个容器并注册我的服务吗?

  3. 各个程序集中的不同类应该如何访问该容器?单例模式?

我已经阅读了很多有关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 {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屋!

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