Container 容器创建

示例 :创建容器

  1. using System;
  2. using DryIoc;
  3. using NUnit.Framework;
  4. class Creating_container
  5. {
  6. [Test]
  7. public void Example()
  8. {
  9. var container = new Container();
  10. }
  11. }

等价于:

  1. class Creating_container_with_explicit_defaults
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container(rules: Rules.Default, scopeContext: null);
  7. }
  8. }

Rules

结合容器制定服务实例的解析与注册规则。不同容器可使用不同的规则。

Rules 是不可改变的,但可通过 With 方法 或 WithoutXXX 方法来调整一个已有的 rules 对象。

示例 :通过 With 方法或 WithoutXXX 方法更改 Rule

  1. class Adding_some_rules
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. // 通过 With 方法更改默认 rules
  7. var container1 = new Container(Rules.Default.With(FactoryMethod.ConstructorWithResolvableArguments));
  8. // 通过 WithoutThrowIfDependencyHasShorterReuseLifespan 方法更改默认 rules
  9. var container2 = new Container(Rules.Default.WithoutThrowIfDependencyHasShorterReuseLifespan());
  10. }
  11. }

DryIoc源码:

  1. /// Better be named `ConstructorWithMostResolvableArguments`.
  2. /// Searches for public constructor with most resolvable parameters or throws <see cref="ContainerException"/> if not found.
  3. /// Works both for resolving service and `Func{TArgs..., TService}`
  4. public static readonly FactoryMethodSelector ConstructorWithResolvableArguments = Constructor(mostResolvable: true);
  5. //Turns off throwing exception when dependency has shorter reuse lifespan than its parent or ancestor.
  6. public Rules WithoutThrowIfDependencyHasShorterReuseLifespan() => WithSettings(_settings & ~Settings.ThrowIfDependencyHasShorterReuseLifespan);

从容器构造开始时就采用新的rules 对象(并非基于 Rules.Default 修改的)

  1. class Adding_some_rules_with_action
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container1 = new Container(rules => rules.WithDefaultReuse(Reuse.Singleton));
  7. var container2 = new Container(rules => rules.WithAutoConcreteTypeResolution());
  8. }
  9. }

ScopeContext 作用域上下文

ScopeContext 作为可选参数用于绑定已有的作用域(scope)。

Container 容器释放

Container 类型实现了IDisposable 接口,在不需要使用的时候应当释放。释放容器将会执行以下操作:

  • 释放 Singletons 对象。
  • 移除所有注册对象。
  • 将 Rules 设置 Rules.Empty。

    1. class Disposing_container
    2. {
    3. public class MyService : IDisposable
    4. {
    5. public bool IsDisposed { get; private set; }
    6. public void Dispose() => IsDisposed = true;
    7. }
    8. [Test]
    9. public void Example()
    10. {
    11. MyService myService;
    12. using (var container = new Container())
    13. {
    14. container.Register<MyService>(Reuse.Singleton); // MyService is registered with singleton lifetime
    15. myService = container.Resolve<MyService>();
    16. }
    17. // Assert通过,随着容器的释放,容器的服务实例也将释放
    18. Assert.IsTrue(myService.IsDisposed);
    19. }
    20. }