Container 容器创建
示例 :创建容器
using System;using DryIoc;using NUnit.Framework;class Creating_container{[Test]public void Example(){var container = new Container();}}
等价于:
class Creating_container_with_explicit_defaults{[Test]public void Example(){var container = new Container(rules: Rules.Default, scopeContext: null);}}
Rules
结合容器制定服务实例的解析与注册规则。不同容器可使用不同的规则。
Rules 是不可改变的,但可通过 With 方法 或 WithoutXXX 方法来调整一个已有的 rules 对象。
示例 :通过 With 方法或 WithoutXXX 方法更改 Rule
class Adding_some_rules{[Test]public void Example(){// 通过 With 方法更改默认 rulesvar container1 = new Container(Rules.Default.With(FactoryMethod.ConstructorWithResolvableArguments));// 通过 WithoutThrowIfDependencyHasShorterReuseLifespan 方法更改默认 rulesvar container2 = new Container(Rules.Default.WithoutThrowIfDependencyHasShorterReuseLifespan());}}
DryIoc源码:
/// Better be named `ConstructorWithMostResolvableArguments`./// Searches for public constructor with most resolvable parameters or throws <see cref="ContainerException"/> if not found./// Works both for resolving service and `Func{TArgs..., TService}`public static readonly FactoryMethodSelector ConstructorWithResolvableArguments = Constructor(mostResolvable: true);//Turns off throwing exception when dependency has shorter reuse lifespan than its parent or ancestor.public Rules WithoutThrowIfDependencyHasShorterReuseLifespan() => WithSettings(_settings & ~Settings.ThrowIfDependencyHasShorterReuseLifespan);
从容器构造开始时就采用新的rules 对象(并非基于 Rules.Default 修改的)
class Adding_some_rules_with_action{[Test]public void Example(){var container1 = new Container(rules => rules.WithDefaultReuse(Reuse.Singleton));var container2 = new Container(rules => rules.WithAutoConcreteTypeResolution());}}
ScopeContext 作用域上下文
ScopeContext 作为可选参数用于绑定已有的作用域(scope)。
Container 容器释放
Container 类型实现了IDisposable 接口,在不需要使用的时候应当释放。释放容器将会执行以下操作:
- 释放 Singletons 对象。
- 移除所有注册对象。
将 Rules 设置 Rules.Empty。
class Disposing_container{public class MyService : IDisposable{public bool IsDisposed { get; private set; }public void Dispose() => IsDisposed = true;}[Test]public void Example(){MyService myService;using (var container = new Container()){container.Register<MyService>(Reuse.Singleton); // MyService is registered with singleton lifetimemyService = container.Resolve<MyService>();}// Assert通过,随着容器的释放,容器的服务实例也将释放Assert.IsTrue(myService.IsDisposed);}}
