主要接口
组件注册在容器里的描述
public interface IComponentRegistration : IDisposable, IAsyncDisposable{
/// <summary>
/// Gets a unique identifier for this component (shared in all sub-contexts.)
/// This value also appears in Services.
/// </summary>
Guid Id { get; }
/// <summary>
/// Gets the activator used to create instances.
/// </summary>
IInstanceActivator Activator { get; }
/// <summary>
/// Gets the lifetime associated with the component.
/// </summary>
IComponentLifetime Lifetime { get; }
/// <summary>
/// Gets a value indicating whether the component instances are shared or not.
/// </summary>
InstanceSharing Sharing { get; }
/// <summary>
/// Gets a value indicating whether the instances
/// of the component should be disposed by the container.
/// </summary>
InstanceOwnership Ownership { get; }
/// <summary>
/// Gets the services provided by the component.
/// </summary>
IEnumerable<Service> Services { get; }
/// <summary>
/// Gets additional data associated with the component.
/// </summary>
IDictionary<string, object?> Metadata { get; }
/// <summary>
/// Gets the component registration upon which this registration is based.
/// </summary>
IComponentRegistration Target { get; }
/// <summary>
/// Gets the resolve pipeline for the component.
/// </summary>
IResolvePipeline ResolvePipeline { get; }
/// <summary>
/// Gets the options for the registration.
/// </summary>
RegistrationOptions Options { get; }
/// <summary>
/// Provides an event that will be invoked just before a pipeline is built,
/// and can be used to add additional middleware
/// at that point.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Attaching to this event after a component registration
/// has already been built will throw an exception.
/// </exception>
[SuppressMessage("CA1003", "CA1003", Justification = "Breaking API change.")]
event EventHandler<IResolvePipelineBuilder> PipelineBuilding;
/// <summary>
/// Builds the resolve pipeline.
/// </summary>
/// <param name="registryServices">The available services.</param>
void BuildResolvePipeline(IComponentRegistryServices registryServices);
}
IComponentRegistry 接口表示组件注册表
// IComponentRegistry 接口表示组件注册表,它包含了容器中所有已注册的组件的信息,
//包括它们的类型、生命周期等。
public interface IComponentRegistry : IDisposable, IAsyncDisposable{
/// <summary>
/// Gets the set of registered components.
/// </summary>
IEnumerable<IComponentRegistration> Registrations { get; }
}
IComponentContext 接口表示组件上下文,它包含了容器中已注册的组件的信息以及解析组件的能力
public interface IComponentContext
{
IComponentRegistry ComponentRegistry { get; }
object ResolveComponent(ResolveRequest request);
}
ILifetimeScope 在 IComponentContext 基础上增加了 生命周期范围
public interface ILifetimeScope : IComponentContext, IDisposable, IAsyncDisposable{
ILifetimeScope BeginLifetimeScope();
ILifetimeScope BeginLifetimeScope(object tag);
}
ISharingLifetimeScope 支持父子嵌套的 ILifetimeScope,子可以获取父容器的服务
public interface ISharingLifetimeScope : ILifetimeScope{
}
//真正干活的组件
public class LifetimeScope : Disposable, ISharingLifetimeScope, IServiceProvider{
//解析组件 实现 ILifetimeScope 接口
public object ResolveComponent(ResolveRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckNotDisposed();
var operation = new ResolveOperation(this, DiagnosticSource);
var handler = ResolveOperationBeginning;
handler?.Invoke(this, new ResolveOperationBeginningEventArgs(operation));
return operation.Execute(request);
}
// 解析组件 实现 IServiceProvider 接口
public object? GetService(Type serviceType)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
//还是用 ResolveOperation 去解析的
return this.ResolveOptional(serviceType);
}
}
IContainer 本质就是 ILifetimeScope
public interface IContainer : ILifetimeScope
{
DiagnosticListener DiagnosticSource { get; }
}
实现 IContainer 及 asp.net core 的 IServiceProvider 接口方法
public class Container : Disposable, IContainer, IServiceProvider{
private readonly LifetimeScope _rootLifetimeScope;
private readonly LifetimeScope _rootLifetimeScope;
internal Container(IComponentRegistry componentRegistry)
{
ComponentRegistry = componentRegistry;
//生成干活的实现类
_rootLifetimeScope = new LifetimeScope(ComponentRegistry);
}
//根范围上在开范围 实现 IContainer 接口方法
public ILifetimeScope BeginLifetimeScope()
{
return _rootLifetimeScope.BeginLifetimeScope();
}
// 实现 IComponentContext 的解析方法
public object ResolveComponent(ResolveRequest request)
{
return _rootLifetimeScope.ResolveComponent(request);
}
// 实现 IServiceProvider 接口方法
public object GetService(Type serviceType)
{
// GetService implementation on LifetimeScope either returns an object, or throws.
return ((IServiceProvider)_rootLifetimeScope).GetService(serviceType)!;
}
}
构造组件注册表,
public interface IComponentRegistryBuilder : IDisposable, IAsyncDisposable{
IComponentRegistry Build();
//组成组件
void Register(IComponentRegistration registration);
}
ComponentRegistryBuilder
internal class ComponentRegistryBuilder : Disposable, IComponentRegistryBuilder{
//内部使用的是 ConcurrentBag 进行保存组件描述
private readonly IRegisteredServicesTracker _registeredServicesTracker;
//把添加的组件放到 _registeredServicesTracker 里
public void Register(IComponentRegistration registration, bool preserveDefaults)
{
if (registration == null)
{
throw new ArgumentNullException(nameof(registration));
}
_registeredServicesTracker.AddRegistration(registration, preserveDefaults);
}
}
//通过 _registeredServicesTracker 生成 IComponentRegistry
public IComponentRegistry Build()
{
// Mark our tracker as complete; no more adjustments to the registry
// will be made after this point.
_registeredServicesTracker.Complete();
// Go through all our registrations and build the component pipeline for each one.
foreach (var registration in _registeredServicesTracker.Registrations)
{
registration.BuildResolvePipeline(_registeredServicesTracker);
}
var componentRegistry = new ComponentRegistry(_registeredServicesTracker, Properties);
return componentRegistry;
}
ContainerBuilder 用于构建容器的配置。可以注册组件、指定组件的生命周期和参数依赖 IComponentRegistryBuilder 去注册组件
public sealed class ContainerBuilder{
public ContainerBuilder()
: this(new Dictionary<string, object?>())
{
_clearRegistrationCaches = IsFirstContainerBuilder();
}
//生成一个 ComponentRegistryBuilder 用来组测组件
internal ContainerBuilder(IDictionary<string, object?> properties)
: this(properties, new ComponentRegistryBuilder(
new DefaultRegisteredServicesTracker(), properties))
{
}
internal ContainerBuilder(IDictionary<string, object?> properties,
IComponentRegistryBuilder componentRegistryBuilder)
{
Properties = properties;
ComponentRegistryBuilder = componentRegistryBuilder;
}
public IComponentRegistryBuilder ComponentRegistryBuilder { get; }
//在注册过程中可以共享信息
public IDictionary<string, object?> Properties { get; }
public IContainer Build(ContainerBuildOptions options = ContainerBuildOptions.None){
var componentRegistry = ComponentRegistryBuilder.Build();
var result = new Container(componentRegistry);
return result
}
}
IRegistrationBuilder 及 RegistrationBuilder 用于更为详细的分步骤的去配置注入组件的过程最后 还是委托给 IComponentRegistryBuilder 及 ComponentRegistryBuilder 进行的注入
RegistrationExtensions 扩展类
public static IRegistrationBuilder<TImplementer, ConcreteReflectionActivatorData,
SingleRegistrationStyle>
RegisterType<[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementer>(
this ContainerBuilder builder)
where TImplementer : notnull
{
var rb = RegistrationBuilder.ForType<TImplementer>();
//注册回调给 IComponentRegistryBuilder cr
rb.RegistrationData.DeferredCallback = builder.RegisterCallback(cr =>
RegistrationBuilder.RegisterSingleComponent(cr, rb));
return rb;
}
静态类 RegistrationBuilder
public static IRegistrationBuilder<TImplementer,
ConcreteReflectionActivatorData, SingleRegistrationStyle> ForType<TImplementer>()
where TImplementer : notnull
{
return new RegistrationBuilder<TImplementer,
ConcreteReflectionActivatorData, SingleRegistrationStyle>(
new TypedService(typeof(TImplementer)),
new ConcreteReflectionActivatorData(typeof(TImplementer)),
new SingleRegistrationStyle());
}
//TLimit 对外暴漏的接口 TActivatorData 实现类型
public interface IRegistrationBuilder<
out TLimit, out TActivatorData, out TRegistrationStyle>{
}
//每个组件的注册都需要生成唯一一个 RegistrationBuilder
internal class RegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle>
: IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle>, IHideObjectMembers
where TLimit : notnull
{
// 注册组件
public static void RegisterSingleComponent<TLimit, TActivatorData,
TSingleRegistrationStyle>(
IComponentRegistryBuilder cr,
IRegistrationBuilder<TLimit, TActivatorData, TSingleRegistrationStyle> builder)
where TSingleRegistrationStyle : SingleRegistrationStyle
where TActivatorData : IConcreteActivatorData
{
//生成组件注册描述符
var registration = CreateRegistration(builder);
//注册描述符
cr.Register(registration, builder.RegistrationStyle.PreserveDefaults);
//触发组件注册事件
var registeredEventArgs = new ComponentRegisteredEventArgs(cr, registration);
foreach (var rh in builder.RegistrationStyle.RegisteredHandlers)
{
rh(cr, registeredEventArgs);
}
}
}
一种结构化的注入方法本质是 用 IComponentRegistryBuilder 传递给模块进行注册
public interface IModule
{
void Configure(IComponentRegistryBuilder componentRegistry);
}
public abstract class Module : IModule{
public void Configure(IComponentRegistryBuilder componentRegistry)
{
var moduleBuilder = new ContainerBuilder(componentRegistry.Properties);
Load(moduleBuilder);
moduleBuilder.UpdateRegistry(componentRegistry);
AttachToRegistrations(componentRegistry);
AttachToSources(componentRegistry);
}
protected virtual void Load(ContainerBuilder builder)
{
//用户写自己注入的组件
}
}
模块注册器
public interface IModuleRegistrar{
public ModuleRegistrarData RegistrarData { get; }
IModuleRegistrar RegisterModule(IModule module);
}
internal class ModuleRegistrar : IModuleRegistrar{
private Action<IComponentRegistryBuilder>? _moduleConfigureChain;
public ModuleRegistrar(ContainerBuilder builder)
{
//给 builder 注册委托链条,在 Build 的时候会执行此委托链条
var callback = builder.RegisterCallback(reg => _moduleConfigureChain?.Invoke(reg));
RegistrarData = new ModuleRegistrarData(callback);
}
public ModuleRegistrarData RegistrarData { get; }
//注册模块
public IModuleRegistrar RegisterModule(IModule module)
{
// Override the original callback to chain the module configuration.
var original = _moduleConfigureChain;
//不断的扩大委托链
_moduleConfigureChain = reg =>
{
// Call the original.
original(reg);
// Call the new module register.
module.Configure(reg);
};
return this;
}
}
ModuleRegistrationExtensions 注册给
public static IModuleRegistrar RegisterModule<TModule>(this ContainerBuilder builder)
where TModule : IModule, new()
{
var registrar = new ModuleRegistrar(builder);
return registrar.RegisterModule<TModule>();
}
上面构建的委托链什么时候执行 ContainerBuilder 的 Build 方法会执行委托链条
private void Build(IComponentRegistryBuilder componentRegistry, bool excludeDefaultModules)
{
foreach (var callback in _configurationCallbacks)
{
callback.Callback(componentRegistry);
}
}
组件描述符解析成对象
autofac 用的是表达式树生成 IL 语言 相关代码的 reflect 文件夹,为了提供性能会把表达式树做成 缓存
注册的对象和暴漏的服务对象
RegistrationData 暴漏的接口服务
public class RegistrationData
{
private bool _defaultServiceOverridden;
//缺省的服务
private Service _defaultService;
//对象暴露的服务集合
private readonly ICollection<Service> _services = new HashSet<Service>();
//对象的生命周期
private IComponentLifetime _lifetime = CurrentScopeLifetime.Instance;
//设置缺省的服务,缺省的服务是必须有的
public RegistrationData(Service defaultService)
{
_defaultService = defaultService ??
throw new ArgumentNullException(nameof(defaultService));
//生成
Metadata = new Dictionary<string, object?>
{
{ MetadataKeys.RegistrationOrderMetadataKey,
SequenceGenerator.GetNextUniqueSequence() },
};
}
public IEnumerable<Service> Services
{
get
{
if (_defaultServiceOverridden)
{
return _services;
}
return _services.DefaultIfEmpty(_defaultService);
}
}
public void AddServices(IEnumerable<Service> services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
_defaultServiceOverridden = true; // important even when services is empty
foreach (var service in services)
{
AddService(service);
}
}
public void AddService(Service service)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
_defaultServiceOverridden = true;
_services.Add(service);
}
public InstanceOwnership Ownership { get; set; } =
InstanceOwnership.OwnedByLifetimeScope;
public IComponentLifetime Lifetime
{
get
{
return _lifetime;
}
set
{
_lifetime = value ?? throw new ArgumentNullException(nameof(value));
}
}
public InstanceSharing Sharing { get; set; } = InstanceSharing.None;
public IDictionary<string, object?> Metadata { get; }
public RegistrationOptions Options { get; set; }
public DeferredCallback? DeferredCallback { get; set; }
public void CopyFrom(RegistrationData that, bool includeDefaultService)
{
if (that == null)
{
throw new ArgumentNullException(nameof(that));
}
Ownership = that.Ownership;
Sharing = that.Sharing;
Lifetime = that.Lifetime;
_defaultServiceOverridden |= that._defaultServiceOverridden;
if (includeDefaultService)
{
_defaultService = that._defaultService;
}
AddAll(_services, that._services);
AddAll(Metadata, that.Metadata.Where(
m => m.Key != MetadataKeys.RegistrationOrderMetadataKey));
}
private static void AddAll<T>(ICollection<T> to, IEnumerable<T> from)
{
foreach (var item in from)
{
to.Add(item);
}
}
public void ClearServices()
{
_services.Clear();
_defaultServiceOverridden = true;
}
}
//实际提供服务的对象
public class ReflectionActivatorData
{
private Type _implementer = default!;
private IConstructorFinder _constructorFinder;
private IConstructorSelector _constructorSelector;
private static readonly IConstructorFinder DefaultConstructorFinder =
new DefaultConstructorFinder();
//默认注入构造函数最长的对象
private static readonly IConstructorSelector DefaultConstructorSelector =
new MostParametersConstructorSelector();
public ReflectionActivatorData(Type implementer)
{
ImplementationType = implementer;
_constructorFinder = DefaultConstructorFinder;
_constructorSelector = DefaultConstructorSelector;
}
public Type ImplementationType
{
get
{
return _implementer;
}
set
{
_implementer = value ?? throw new ArgumentNullException(nameof(value));
}
}
public IConstructorFinder ConstructorFinder
{
get
{
return _constructorFinder;
}
set
{
_constructorFinder = value ?? throw new ArgumentNullException(nameof(value));
}
}
public IConstructorSelector ConstructorSelector
{
get
{
return _constructorSelector;
}
set
{
_constructorSelector = value ?? throw new ArgumentNullException(nameof(value));
}
}
public IList<Parameter> ConfiguredParameters { get; } = new List<Parameter>();
public IList<Parameter> ConfiguredProperties { get; } = new List<Parameter>();
}
注入的组件描述加元素据及生命周期加注册管线及解析管线的最后呈现
public readonly struct ServiceRegistration : IEquatable<ServiceRegistration>
{
public ServiceRegistration(
IResolvePipeline servicePipeline, IComponentRegistration registration)
{
Pipeline = servicePipeline ??
throw new ArgumentNullException(nameof(servicePipeline));
Registration = registration ??
throw new ArgumentNullException(nameof(registration));
}
public IResolvePipeline Pipeline { get; }
public IComponentRegistration Registration { get; }
public IDictionary<string, object?> Metadata => Registration.Metadata;
public long GetRegistrationOrder() => Registration.GetRegistrationOrder();
public override bool Equals(object? obj)
{
return obj is ServiceRegistration registration && Equals(registration);
}
public bool Equals(ServiceRegistration other)
{
return Pipeline == other.Pipeline && Registration == other.Registration;
}
public override int GetHashCode()
{
if (Pipeline is null || Registration is null)
{
return 0;
}
return Pipeline.GetHashCode() ^ Registration.GetHashCode();
}
public static bool operator ==(ServiceRegistration left, ServiceRegistration right)
{
return left.Equals(right);
}
public static bool operator !=(ServiceRegistration left, ServiceRegistration right)
{
return !(left == right);
}
}
IRegistrationSource
IRegistrationSource 接口是一个非常有用的接口,它允许我们动态地(在运行时)注册和解析依赖项 。它是 AUTOFAC 的一个核心组件,用于实现依赖注入(Dependency Injection)的功能。允许用户使 用底层的接口去自定义注入和解析,在常规的 api 不能满足的情况下作为最后的解决方法
常规的比如:
- Func
等,用于动态创建组件;Func<T,U> - Owned
手动控制组件的使用寿命; - IEnumerable
获取服务的所有实现者; - 开放泛型注册
如下的逆变注册,
interface IHandler<in TCommand>;
{
void Handle(TCommand command);
}
class Command { }
class DerivedCommand : Command { }
class CommandHandler : IHandler<Command> { ... }
var builder = new ContainerBuilder();
//
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterType<CommandHandler>();
var container = builder.Build();
// 在解析 IHandler<DerivedCommand> 组件的时候,
// 因为没有注册任何实现此接口的实现类,就会寻找已经注册的注册源去解析,
// 找到所有已经注册的可以匹配的实现类
// 比如这里注册的 CommandHandler
var handler = container.Resolve<IHandler<DerivedCommand>>();
handler.Handle(new DerivedCommand());