1. 容器创建
void Main()
{
// 以下两种方式等价
var container1 = new Container();
var container2 = new Container(rules: Rules.Default, scopeContext: null);
}
1.1 构造函数
//
// 摘要:
// Creates new container with default rules DryIoc.Rules.Default.
public Container();
//
// 摘要:
// Creates new container, optionally providing DryIoc.Container.Rules to modify
// default container behavior.
//
// 参数:
// rules:
// (optional) Rules to modify container default resolution behavior. If not specified,
// then DryIoc.Rules.Default will be used.
//
// scopeContext:
// (optional) Scope context to use for scoped reuse.
public Container(Rules rules = null, IScopeContext scopeContext = null);
//
// 摘要:
// Creates new container with configured rules.
//
// 参数:
// configure:
// Allows to modify DryIoc.Rules.Default rules.
//
// scopeContext:
// (optional) Scope context to use for DryIoc.Reuse.InCurrentScope.
public Container(Func<Rules, Rules> configure, IScopeContext scopeContext = null);
2. 规则
规则定义容器的行为与协议。规则是不可变的,可以通过With.../Without
方法从一个旧的规则获取新的规则。
void Main()
{
{
var container1 = new Container(Rules.Default.With(FactoryMethod.ConstructorWithResolvableArguments));
var container2 = new Container(Rules.Default.WithoutThrowIfDependencyHasShorterReuseLifespan());
}
{
var container1 = new Container(rules => rules.WithDefaultReuse(Reuse.Singleton));
var container2 = new Container(rules => rules.WithAutoConcreteTypeResolution());
}
}
3. 销毁容器
容器实现了 IDisposable
接口,在不需要使用时应该被释放。释放容器将执行以下操作:
- 释放单例
- 移除所有注册
- 设置规则为Rules.Empty
void Main()
{
MyService myService;
using (var container = new Container())
{
container.Register<MyService>(Reuse.Singleton);
myService = container.Resolve<MyService>();
}
Console.WriteLine(myService.IsDisposed); // True
}
public class MyService : IDisposable
{
public bool IsDisposed { get; private set; }
public void Dispose() => IsDisposed = true;
}