02_Prism_容器

注册服务

Transient Services

瞬态服务会每次创建一个新实例的服务。

containerRegistry.Register<FooService>();
containerRegistry.Register<IBarService, BarService>();
Singleton Services

单例服务在程序第一次使用之前,并没有被创建,因此也没有占用内存。

containerRegistry.RegisterSingleton<FooService>();
containerRegistry.RegisterSingleton<IBarService, BarService>();
Service Instance

为一个服务提供一个具体的实例。

containerRegistry.RegisterInstance<IFoo>(new FooImplementation());
containerRegistry.RegisterInstance<IBarrel>(Barrel.Current);
检查服务是否已注册
if (containerRegistry.IsRegistered<ISomeService>())
{
    // Do something...
}
延迟加载

可以通过 Func 或者 Lazy 来延迟加载某个服务。

public class ViewAViewModel
{
    public ViewAViewModel(Func<IFoo> fooFactory, Lazy<IBar> lazyBar)
    {

    }
}
Resolve All

很多时候会对一个服务提供多个实现,并期望能够一次性反射所有。

public class SomeService
{
    public SomeService(IEnumerable<IFoo> fooCollection)
    {
    }
}

异常处理

当容器反射时发生错误时会抛出 CaontainerResolutionException 异常,包含了一些异常信息:

  • MissingRegistration
  • CannotResolveAbstractType
  • CyclicalDependency

可以通过 ModuleManager.LoadModuleCompleted 事件来输出错误信息。

protected override void InitializeModules()
{
    var manager = Container.Resolve<IModuleManager>();
    manager.LoadModuleCompleted += LoadModuleCompleted;
    manager.Run();
}

private void LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e)
{
    LoadModuleCompleted(e.ModuleInfo, e.Error, e.IsErrorHandled);
}

protected virtual void LoadModuleCompleted(IModuleInfo moduleInfo, Execption error, bool isHandled)
{
    if(null != error && error is ContainerResolutionException cre)
    {
        var errors = cre.GetErrors();
        foreach((var type, var ex) in errors)
        {
            Console.WriteLine($"Error with: {type.FullName}");
            Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
        }
    }
}

ContainerProvider

在XAML中直接实例化 ViewModel 并设置 DataContext 是 View 和 ViewModel 之间建立关联的最基本的方法:

<UserControl.DataContext>
    <viewmodels:MainViewModel/>
</UserControl.DataContext>

但上面这种方法只能实例化具有 无参构建函数的类型。ContainerProvider 通过设置 Type 或 Name 从Container 中解析请求类型。

<Window>
  <Window.DataContext>
    <prism:ContainerProvider Type="{x:Type local:MyViewModel}" />
  </Window.DataContext>
</Window>
我的公众号 HelloPragram

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值