{
internal sealed class DebuggerTraceWriter : TraceWriter
{
- private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name;
+ private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name!;
public override bool CanWriteInformation
{
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, object attributedPart) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart) { throw null; }
public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart, System.Reflection.ReflectionContext reflectionContext) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin, bool ensureIsDiscoverable) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement? origin, bool ensureIsDiscoverable) { throw null; }
public static bool Exports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; }
public static bool Exports<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part) { throw null; }
public static string GetContractName(System.Type type) { throw null; }
- public static TMetadataView GetMetadataView<TMetadataView>(System.Collections.Generic.IDictionary<string, object> metadata) { throw null; }
+ public static TMetadataView GetMetadataView<TMetadataView>(System.Collections.Generic.IDictionary<string, object?> metadata) { throw null; }
public static string GetTypeIdentity(System.Reflection.MethodInfo method) { throw null; }
public static string GetTypeIdentity(System.Type type) { throw null; }
public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; }
public partial class ChangeRejectedException : System.ComponentModel.Composition.CompositionException
{
public ChangeRejectedException() { }
- public ChangeRejectedException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError> errors) { }
- public ChangeRejectedException(string message) { }
- public ChangeRejectedException(string message, System.Exception innerException) { }
+ public ChangeRejectedException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError>? errors) { }
+ public ChangeRejectedException(string? message) { }
+ public ChangeRejectedException(string? message, System.Exception? innerException) { }
public override string Message { get { throw null; } }
}
public partial class CompositionContractMismatchException : System.Exception
{
public CompositionContractMismatchException() { }
protected CompositionContractMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- public CompositionContractMismatchException(string message) { }
- public CompositionContractMismatchException(string message, System.Exception innerException) { }
+ public CompositionContractMismatchException(string? message) { }
+ public CompositionContractMismatchException(string? message, System.Exception? innerException) { }
}
public partial class CompositionError
{
- public CompositionError(string message) { }
- public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { }
- public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception exception) { }
- public CompositionError(string message, System.Exception exception) { }
+ public CompositionError(string? message) { }
+ public CompositionError(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element) { }
+ public CompositionError(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element, System.Exception? exception) { }
+ public CompositionError(string? message, System.Exception? exception) { }
public string Description { get { throw null; } }
- public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } }
- public System.Exception Exception { get { throw null; } }
+ public System.ComponentModel.Composition.Primitives.ICompositionElement? Element { get { throw null; } }
+ public System.Exception? Exception { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class CompositionException : System.Exception
{
public CompositionException() { }
- public CompositionException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError> errors) { }
- public CompositionException(string message) { }
- public CompositionException(string message, System.Exception innerException) { }
+ public CompositionException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError>? errors) { }
+ public CompositionException(string? message) { }
+ public CompositionException(string? message, System.Exception? innerException) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.CompositionError> Errors { get { throw null; } }
public override string Message { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.Exception> RootCauses { get { throw null; } }
public partial class ExportAttribute : System.Attribute
{
public ExportAttribute() { }
- public ExportAttribute(string contractName) { }
- public ExportAttribute(string contractName, System.Type contractType) { }
- public ExportAttribute(System.Type contractType) { }
- public string ContractName { get { throw null; } }
- public System.Type ContractType { get { throw null; } }
+ public ExportAttribute(string? contractName) { }
+ public ExportAttribute(string? contractName, System.Type? contractType) { }
+ public ExportAttribute(System.Type? contractType) { }
+ public string? ContractName { get { throw null; } }
+ public System.Type? ContractType { get { throw null; } }
}
public partial class ExportFactory<T>
{
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple=true, Inherited=false)]
public sealed partial class ExportMetadataAttribute : System.Attribute
{
- public ExportMetadataAttribute(string name, object value) { }
+ public ExportMetadataAttribute(string? name, object? value) { }
public bool IsMultiple { get { throw null; } set { } }
public string Name { get { throw null; } }
- public object Value { get { throw null; } }
+ public object? Value { get { throw null; } }
}
public partial interface ICompositionService
{
public partial class ImportAttribute : System.Attribute
{
public ImportAttribute() { }
- public ImportAttribute(string contractName) { }
- public ImportAttribute(string contractName, System.Type contractType) { }
- public ImportAttribute(System.Type contractType) { }
+ public ImportAttribute(string? contractName) { }
+ public ImportAttribute(string? contractName, System.Type? contractType) { }
+ public ImportAttribute(System.Type? contractType) { }
public bool AllowDefault { get { throw null; } set { } }
public bool AllowRecomposition { get { throw null; } set { } }
- public string ContractName { get { throw null; } }
- public System.Type ContractType { get { throw null; } }
+ public string? ContractName { get { throw null; } }
+ public System.Type? ContractType { get { throw null; } }
public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } }
public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } }
}
{
public ImportCardinalityMismatchException() { }
protected ImportCardinalityMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- public ImportCardinalityMismatchException(string message) { }
- public ImportCardinalityMismatchException(string message, System.Exception innerException) { }
+ public ImportCardinalityMismatchException(string? message) { }
+ public ImportCardinalityMismatchException(string? message, System.Exception? innerException) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Constructor, AllowMultiple=false, Inherited=false)]
public partial class ImportingConstructorAttribute : System.Attribute
public partial class ImportManyAttribute : System.Attribute
{
public ImportManyAttribute() { }
- public ImportManyAttribute(string contractName) { }
- public ImportManyAttribute(string contractName, System.Type contractType) { }
- public ImportManyAttribute(System.Type contractType) { }
+ public ImportManyAttribute(string? contractName) { }
+ public ImportManyAttribute(string? contractName, System.Type? contractType) { }
+ public ImportManyAttribute(System.Type? contractType) { }
public bool AllowRecomposition { get { throw null; } set { } }
- public string ContractName { get { throw null; } }
- public System.Type ContractType { get { throw null; } }
+ public string? ContractName { get { throw null; } }
+ public System.Type? ContractType { get { throw null; } }
public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } }
public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } }
}
public partial class InheritedExportAttribute : System.ComponentModel.Composition.ExportAttribute
{
public InheritedExportAttribute() { }
- public InheritedExportAttribute(string contractName) { }
- public InheritedExportAttribute(string contractName, System.Type contractType) { }
- public InheritedExportAttribute(System.Type contractType) { }
+ public InheritedExportAttribute(string? contractName) { }
+ public InheritedExportAttribute(string? contractName, System.Type? contractType) { }
+ public InheritedExportAttribute(System.Type? contractType) { }
}
public partial interface IPartImportsSatisfiedNotification
{
[System.AttributeUsageAttribute(System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)]
public sealed partial class MetadataViewImplementationAttribute : System.Attribute
{
- public MetadataViewImplementationAttribute(System.Type implementationType) { }
- public System.Type ImplementationType { get { throw null; } }
+ public MetadataViewImplementationAttribute(System.Type? implementationType) { }
+ public System.Type? ImplementationType { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
public sealed partial class PartCreationPolicyAttribute : System.Attribute
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)]
public sealed partial class PartMetadataAttribute : System.Attribute
{
- public PartMetadataAttribute(string name, object value) { }
+ public PartMetadataAttribute(string? name, object? value) { }
public string Name { get { throw null; } }
- public object Value { get { throw null; } }
+ public object? Value { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
public sealed partial class PartNotDiscoverableAttribute : System.Attribute
public partial class AggregateCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged
{
public AggregateCatalog() { }
- public AggregateCatalog(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> catalogs) { }
- public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[] catalogs) { }
+ public AggregateCatalog(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartCatalog>? catalogs) { }
+ public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[]? catalogs) { }
public System.Collections.Generic.ICollection<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> Catalogs { get { throw null; } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
}
public partial class AggregateExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
{
- public AggregateExportProvider(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.ExportProvider> providers) { }
- public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
+ public AggregateExportProvider(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.ExportProvider>? providers) { }
+ public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Hosting.ExportProvider> Providers { get { throw null; } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+ protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
}
public partial class ApplicationCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Primitives.ICompositionElement
{
public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext) { }
public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
- System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
+ System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public AssemblyCatalog(string codeBase, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public System.Reflection.Assembly Assembly { get { throw null; } }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
- System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
+ System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public partial class AtomicComposition : System.IDisposable
{
public AtomicComposition() { }
- public AtomicComposition(System.ComponentModel.Composition.Hosting.AtomicComposition outerAtomicComposition) { }
+ public AtomicComposition(System.ComponentModel.Composition.Hosting.AtomicComposition? outerAtomicComposition) { }
public void AddCompleteAction(System.Action completeAction) { }
public void AddRevertAction(System.Action revertAction) { }
public void Complete() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- public void SetValue(object key, object value) { }
- public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value) { throw null; }
- public bool TryGetValue<T>(object key, out T value) { throw null; }
+ public void SetValue(object key, object? value) { }
+ public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T value) { throw null; }
+ public bool TryGetValue<T>(object key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T value) { throw null; }
}
public partial class CatalogExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
{
public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe) { }
public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } }
- public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+ public System.ComponentModel.Composition.Hosting.ExportProvider? SourceProvider { get { throw null; } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+ protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
}
public static partial class CatalogExtensions
{
}
public partial class ComposablePartCatalogChangeEventArgs : System.EventArgs
{
- public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> addedDefinitions, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
+ public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> addedDefinitions, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> AddedDefinitions { get { throw null; } }
- public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } }
+ public System.ComponentModel.Composition.Hosting.AtomicComposition? AtomicComposition { get { throw null; } }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> RemovedDefinitions { get { throw null; } }
}
public partial class ComposablePartExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable
public ComposablePartExportProvider() { }
public ComposablePartExportProvider(bool isThreadSafe) { }
public ComposablePartExportProvider(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
- public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+ public System.ComponentModel.Composition.Hosting.ExportProvider? SourceProvider { get { throw null; } set { } }
public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+ protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
}
public partial class CompositionBatch
{
public CompositionBatch() { }
- public CompositionBatch(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart> partsToAdd, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart> partsToRemove) { }
+ public CompositionBatch(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart>? partsToAdd, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart>? partsToRemove) { }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> PartsToAdd { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> PartsToRemove { get { throw null; } }
public System.ComponentModel.Composition.Primitives.ComposablePart AddExport(System.ComponentModel.Composition.Primitives.Export export) { throw null; }
public partial class CompositionContainer : System.ComponentModel.Composition.Hosting.ExportProvider, System.ComponentModel.Composition.ICompositionService, System.IDisposable
{
public CompositionContainer() { }
- public CompositionContainer(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
- public CompositionContainer(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
- public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
- public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
- public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
- public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } }
+ public CompositionContainer(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
+ public CompositionContainer(params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
+ public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, bool isThreadSafe, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
+ public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
+ public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
+ public System.ComponentModel.Composition.Primitives.ComposablePartCatalog? Catalog { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Hosting.ExportProvider> Providers { get { throw null; } }
public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+ protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
public void ReleaseExport(System.ComponentModel.Composition.Primitives.Export export) { }
public void ReleaseExports(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports) { }
public void ReleaseExports<T>(System.Collections.Generic.IEnumerable<System.Lazy<T>> exports) { }
public CompositionScopeDefinition(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> children, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> publicSurface) { }
public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> Children { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> PublicSurface { get { throw null; } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public string Path { get { throw null; } }
public string SearchPattern { get { throw null; } }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
- System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+ System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public abstract partial class ExportProvider
{
protected ExportProvider() { }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanged { add { } remove { } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanging { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs>? ExportsChanged { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs>? ExportsChanging { add { } remove { } }
+ [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
public T GetExportedValueOrDefault<T>() { throw null; }
- public T GetExportedValueOrDefault<T>(string contractName) { throw null; }
+ [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
+ public T GetExportedValueOrDefault<T>(string? contractName) { throw null; }
public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>() { throw null; }
- public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>(string contractName) { throw null; }
+ public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>(string? contractName) { throw null; }
+ [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
public T GetExportedValue<T>() { throw null; }
- public T GetExportedValue<T>(string contractName) { throw null; }
+ [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
+ public T GetExportedValue<T>(string? contractName) { throw null; }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
- public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
- public System.Collections.Generic.IEnumerable<System.Lazy<object, object>> GetExports(System.Type type, System.Type metadataViewType, string contractName) { throw null; }
- protected abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition);
+ public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
+ public System.Collections.Generic.IEnumerable<System.Lazy<object, object>> GetExports(System.Type type, System.Type? metadataViewType, string? contractName) { throw null; }
+ protected abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition);
public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>() { throw null; }
- public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>(string contractName) { throw null; }
+ public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>(string? contractName) { throw null; }
public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>() { throw null; }
- public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName) { throw null; }
- public System.Lazy<T> GetExport<T>() { throw null; }
- public System.Lazy<T> GetExport<T>(string contractName) { throw null; }
- public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>() { throw null; }
- public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName) { throw null; }
+ public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string? contractName) { throw null; }
+ public System.Lazy<T>? GetExport<T>() { throw null; }
+ public System.Lazy<T>? GetExport<T>(string? contractName) { throw null; }
+ public System.Lazy<T, TMetadataView>? GetExport<T, TMetadataView>() { throw null; }
+ public System.Lazy<T, TMetadataView>? GetExport<T, TMetadataView>(string? contractName) { throw null; }
protected virtual void OnExportsChanged(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { }
protected virtual void OnExportsChanging(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { }
- public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition, out System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports) { throw null; }
+ public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition, out System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? exports) { throw null; }
}
public partial class ExportsChangeEventArgs : System.EventArgs
{
- public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> addedExports, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
+ public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> addedExports, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> AddedExports { get { throw null; } }
- public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } }
+ public System.ComponentModel.Composition.Hosting.AtomicComposition? AtomicComposition { get { throw null; } }
public System.Collections.Generic.IEnumerable<string> ChangedContractNames { get { throw null; } }
public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> RemovedExports { get { throw null; } }
}
{
public FilteredCatalog(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Func<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, bool> filter) { }
public System.ComponentModel.Composition.Hosting.FilteredCatalog Complement { get { throw null; } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
- public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+ public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
public ImportEngine(System.ComponentModel.Composition.Hosting.ExportProvider sourceProvider, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
- public void PreviewImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
- public void ReleaseImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
+ public void PreviewImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
+ public void ReleaseImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
public void SatisfyImports(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
public void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part) { }
}
public partial interface INotifyComposablePartCatalogChanged
{
- event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed;
- event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing;
+ event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed;
+ event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing;
}
public static partial class ScopingExtensions
{
public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> types, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { }
public TypeCatalog(params System.Type[] types) { }
string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } }
- System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
+ System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
protected override void Dispose(bool disposing) { }
public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
public override string ToString() { throw null; }
protected ComposablePart() { }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
- public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+ public virtual System.Collections.Generic.IDictionary<string, object?> Metadata { get { throw null; } }
public virtual void Activate() { }
- public abstract object GetExportedValue(System.ComponentModel.Composition.Primitives.ExportDefinition definition);
+ public abstract object? GetExportedValue(System.ComponentModel.Composition.Primitives.ExportDefinition definition);
public abstract void SetImport(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> exports);
}
public abstract partial class ComposablePartCatalog : System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition>, System.Collections.IEnumerable, System.IDisposable
protected ComposablePartDefinition() { }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
- public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+ public virtual System.Collections.Generic.IDictionary<string, object?> Metadata { get { throw null; } }
public abstract System.ComponentModel.Composition.Primitives.ComposablePart CreatePart();
}
public partial class ComposablePartException : System.Exception
{
public ComposablePartException() { }
protected ComposablePartException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
- public ComposablePartException(string message) { }
- public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { }
- public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception innerException) { }
- public ComposablePartException(string message, System.Exception innerException) { }
- public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } }
+ public ComposablePartException(string? message) { }
+ public ComposablePartException(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element) { }
+ public ComposablePartException(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element, System.Exception? innerException) { }
+ public ComposablePartException(string? message, System.Exception? innerException) { }
+ public System.ComponentModel.Composition.Primitives.ICompositionElement? Element { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class ContractBasedImportDefinition : System.ComponentModel.Composition.Primitives.ImportDefinition
{
protected ContractBasedImportDefinition() { }
- public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy) { }
- public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata) { }
+ public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy) { }
+ public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata) { }
public override System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> Constraint { get { throw null; } }
public virtual System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> RequiredMetadata { get { throw null; } }
- public virtual string RequiredTypeIdentity { get { throw null; } }
+ public virtual string? RequiredTypeIdentity { get { throw null; } }
public override bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public override string ToString() { throw null; }
}
public partial class Export
{
protected Export() { }
- public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func<object> exportedValueGetter) { }
- public Export(string contractName, System.Collections.Generic.IDictionary<string, object> metadata, System.Func<object> exportedValueGetter) { }
- public Export(string contractName, System.Func<object> exportedValueGetter) { }
+ public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func<object?> exportedValueGetter) { }
+ public Export(string contractName, System.Collections.Generic.IDictionary<string, object?>? metadata, System.Func<object?> exportedValueGetter) { }
+ public Export(string contractName, System.Func<object?> exportedValueGetter) { }
public virtual System.ComponentModel.Composition.Primitives.ExportDefinition Definition { get { throw null; } }
- public System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
- public object Value { get { throw null; } }
- protected virtual object GetExportedValueCore() { throw null; }
+ public System.Collections.Generic.IDictionary<string, object?> Metadata { get { throw null; } }
+ public object? Value { get { throw null; } }
+ protected virtual object? GetExportedValueCore() { throw null; }
}
public partial class ExportDefinition
{
protected ExportDefinition() { }
- public ExportDefinition(string contractName, System.Collections.Generic.IDictionary<string, object> metadata) { }
+ public ExportDefinition(string contractName, System.Collections.Generic.IDictionary<string, object?>? metadata) { }
public virtual string ContractName { get { throw null; } }
- public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+ public virtual System.Collections.Generic.IDictionary<string, object?> Metadata { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class ExportedDelegate
{
protected ExportedDelegate() { }
- public ExportedDelegate(object instance, System.Reflection.MethodInfo method) { }
- public virtual System.Delegate CreateDelegate(System.Type delegateType) { throw null; }
+ public ExportedDelegate(object? instance, System.Reflection.MethodInfo method) { }
+ public virtual System.Delegate? CreateDelegate(System.Type delegateType) { throw null; }
}
public partial interface ICompositionElement
{
string DisplayName { get; }
- System.ComponentModel.Composition.Primitives.ICompositionElement Origin { get; }
+ System.ComponentModel.Composition.Primitives.ICompositionElement? Origin { get; }
}
public enum ImportCardinality
{
public partial class ImportDefinition
{
protected ImportDefinition() { }
- public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { }
- public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary<string, object> metadata) { }
+ public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { }
+ public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary<string, object?>? metadata) { }
public virtual System.ComponentModel.Composition.Primitives.ImportCardinality Cardinality { get { throw null; } }
public virtual System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> Constraint { get { throw null; } }
public virtual string ContractName { get { throw null; } }
public virtual bool IsPrerequisite { get { throw null; } }
public virtual bool IsRecomposable { get { throw null; } }
- public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+ public virtual System.Collections.Generic.IDictionary<string, object?> Metadata { get { throw null; } }
public virtual bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public override string ToString() { throw null; }
}
public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func<System.Reflection.MemberInfo[]> accessorsCreator) { throw null; }
public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null; }
public System.Reflection.MemberTypes MemberType { get { throw null; } }
- public override bool Equals(object obj) { throw null; }
+ public override bool Equals(object? obj) { throw null; }
public System.Reflection.MemberInfo[] GetAccessors() { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo left, System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo right) { throw null; }
}
public static partial class ReflectionModelServices
{
- public static System.ComponentModel.Composition.Primitives.ExportDefinition CreateExportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo exportingMember, string contractName, System.Lazy<System.Collections.Generic.IDictionary<string, object>> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
- public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Lazy<System.Type> partType, bool isDisposalRequired, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition>> imports, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition>> exports, System.Lazy<System.Collections.Generic.IDictionary<string, object>> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ExportDefinition CreateExportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo exportingMember, string contractName, System.Lazy<System.Collections.Generic.IDictionary<string, object?>> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+ public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Lazy<System.Type> partType, bool isDisposalRequired, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition>>? imports, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition>>? exports, System.Lazy<System.Collections.Generic.IDictionary<string, object?>>? metadata, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition GetExportFactoryProductImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetExportingMember(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; }
public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetImportingMember(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static bool IsDisposalRequired(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition) { throw null; }
public static bool IsExportFactoryImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
public static bool IsImportingParameter(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; }
- public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable<System.Type> genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { throw null; }
+ public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable<System.Type> genericParameters, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.ComponentModel.Composition.Primitives.ComposablePartDefinition? specialization) { throw null; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.ComponentModel.Composition.cs" />
return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
}
- public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class
+ public static T? GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class
{
return GetAttributes<T>(attributeProvider).FirstOrDefault();
}
- public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
+ public static T? GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
{
return GetAttributes<T>(attributeProvider, inherit).FirstOrDefault();
}
Type collectionType = typeof(CollectionOfObject<>).MakeGenericType(underlyingItemType);
- return (ICollection<object>)Activator.CreateInstance(collectionType, collectionObject);
+ return (ICollection<object>)Activator.CreateInstance(collectionType, collectionObject)!;
}
private class CollectionOfObjectList : ICollection<object>
return false;
}
- public static Type GetEnumerableElementType(Type type)
+ public static Type? GetEnumerableElementType(Type type)
{
if (type.UnderlyingSystemType == StringType || !IEnumerableType.IsAssignableFrom(type))
{
return null;
}
- Type closedType;
- if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out closedType))
+ if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out Type? closedType))
{
return closedType.GetGenericArguments()[0];
}
return null;
}
- public static Type GetCollectionElementType(Type type)
+ public static Type? GetCollectionElementType(Type type)
{
- Type closedType;
- if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out closedType))
+ if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out Type? closedType))
{
return closedType.GetGenericArguments()[0];
}
return new ReadOnlyCollection<T>(source.AsArray());
}
- public static IEnumerable<T> ConcatAllowingNull<T>(this IEnumerable<T> source, IEnumerable<T> second)
+ public static IEnumerable<T>? ConcatAllowingNull<T>(this IEnumerable<T>? source, IEnumerable<T>? second)
{
if (second == null || !second.FastAny())
{
return source.Concat(second);
}
- public static ICollection<T> ConcatAllowingNull<T>(this ICollection<T> source, ICollection<T> second)
+ public static ICollection<T>? ConcatAllowingNull<T>(this ICollection<T>? source, ICollection<T>? second)
{
if (second == null || (second.Count == 0))
{
return result;
}
- public static List<T> FastAppendToListAllowNulls<T>(this List<T> source, IEnumerable<T> second)
+ public static List<T>? FastAppendToListAllowNulls<T>(this List<T>? source, IEnumerable<T>? second)
{
if (second == null)
{
}
// if the second is List<T>, and contains very few elements there's no need for AddRange
- List<T> secondAsList = second as List<T>;
- if (secondAsList != null)
+ if (second is List<T> secondAsList)
{
if (secondAsList.Count == 0)
{
}
- private static List<T> FastAppendToListAllowNulls<T>(this List<T> source, T value)
+ private static List<T> FastAppendToListAllowNulls<T>(this List<T>? source, T value)
{
if (source == null)
{
return source;
}
- public static List<T> FastAppendToListAllowNulls<T>(
- this List<T> source, T value,
- IEnumerable<T> second)
+ public static List<T>? FastAppendToListAllowNulls<T>(
+ this List<T>? source, T value,
+ IEnumerable<T>? second)
{
if (second == null)
{
}
// Cast to ICollection instead of ICollection<T> for performance reasons.
- ICollection collection = source as ICollection;
- if (collection != null)
+ if (source is ICollection collection)
{
return collection.Count switch
{
// sources.
// Cast to ICollection instead of ICollection<T> for performance reasons.
- ICollection collection = source as ICollection;
- if (collection != null)
+ if (source is ICollection collection)
{
return collection.Count > 0;
}
public static T[] AsArray<T>(this IEnumerable<T> enumerable)
{
- T[] array = enumerable as T[];
-
- if (array != null)
+ if (enumerable is T[] array)
{
return array;
}
public static List<T> AsList<T>(this IEnumerable<T> enumerable)
{
- List<T> list = enumerable as List<T>;
-
- if (list != null)
+ if (enumerable is List<T> list)
{
return list;
}
for (int i = 0; i < thisArray.Length; i++)
{
- if (!thisArray[i].Equals(thatArray[i]))
+ if (!thisArray[i]!.Equals(thatArray[i]))
{
return false;
}
for (int i = 0; i < thisList.Count; i++)
{
- if (!thisList[i].Equals(thatList[i]))
+ if (!thisList[i]!.Equals(thatList[i]))
{
return false;
}
foreach (var weakItem in _items)
{
- T item = weakItem.Target as T;
-
- if (item != null)
+ if (weakItem.Target is T item)
{
aliveItems.Add(item);
}
{
internal static class ContractServices
{
- public static bool TryCast(Type contractType, object value, out object result)
+ public static bool TryCast(Type contractType, object? value, out object? result)
{
if (value == null)
{
// We couldn't cast see if a delegate works for us.
if (typeof(Delegate).IsAssignableFrom(contractType))
{
- ExportedDelegate exportedDelegate = value as ExportedDelegate;
- if (exportedDelegate != null)
+ if (value is ExportedDelegate exportedDelegate)
{
result = exportedDelegate.CreateDelegate(contractType.UnderlyingSystemType);
return (result != null);
internal static class GenerationServices
{
// Type.GetTypeFromHandle
- private static readonly MethodInfo _typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle");
+ private static readonly MethodInfo s_typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle")!;
// typeofs are pretty expensive, so we cache them statically
- private static readonly Type TypeType = typeof(System.Type);
- private static readonly Type StringType = typeof(string);
- private static readonly Type CharType = typeof(char);
- private static readonly Type BooleanType = typeof(bool);
- private static readonly Type ByteType = typeof(byte);
- private static readonly Type SByteType = typeof(sbyte);
- private static readonly Type Int16Type = typeof(short);
- private static readonly Type UInt16Type = typeof(ushort);
- private static readonly Type Int32Type = typeof(int);
- private static readonly Type UInt32Type = typeof(uint);
- private static readonly Type Int64Type = typeof(long);
- private static readonly Type UInt64Type = typeof(ulong);
- private static readonly Type DoubleType = typeof(double);
- private static readonly Type SingleType = typeof(float);
- private static readonly Type IEnumerableTypeofT = typeof(System.Collections.Generic.IEnumerable<>);
- private static readonly Type IEnumerableType = typeof(System.Collections.IEnumerable);
-
- private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data").GetGetMethod();
- private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add");
- private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
+ private static readonly Type s_typeType = typeof(System.Type);
+ private static readonly Type s_stringType = typeof(string);
+ private static readonly Type s_charType = typeof(char);
+ private static readonly Type s_booleanType = typeof(bool);
+ private static readonly Type s_byteType = typeof(byte);
+ private static readonly Type s_sByteType = typeof(sbyte);
+ private static readonly Type s_int16Type = typeof(short);
+ private static readonly Type s_uInt16Type = typeof(ushort);
+ private static readonly Type s_int32Type = typeof(int);
+ private static readonly Type s_uInt32Type = typeof(uint);
+ private static readonly Type s_int64Type = typeof(long);
+ private static readonly Type s_uInt64Type = typeof(ulong);
+ private static readonly Type s_doubleType = typeof(double);
+ private static readonly Type s_singleType = typeof(float);
+ private static readonly Type s_iEnumerableTypeofT = typeof(System.Collections.Generic.IEnumerable<>);
+ private static readonly Type s_iEnumerableType = typeof(System.Collections.IEnumerable);
+
+ private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data")!.GetGetMethod()!;
+ private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add")!;
+ private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!;
public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder typeBuilder, Type[] ctrArgumentTypes)
{
/// Everything else cannot be represented as literals
/// <param name="ilGenerator"></param>
/// <param name="value"></param>
- public static void LoadValue(this ILGenerator ilGenerator, object value)
+ public static void LoadValue(this ILGenerator ilGenerator, object? value)
{
Debug.Assert(ilGenerator != null);
//
// Generate IL depending on the valueType - this is messier than it should ever be, but sadly necessary
//
- if (valueType == GenerationServices.StringType)
+ if (valueType == GenerationServices.s_stringType)
{
// we need to check for strings before enumerables, because strings are IEnumerable<char>
ilGenerator.LoadString((string)rawValue);
}
- else if (GenerationServices.TypeType.IsAssignableFrom(valueType))
+ else if (GenerationServices.s_typeType.IsAssignableFrom(valueType))
{
ilGenerator.LoadTypeOf((Type)rawValue);
}
- else if (GenerationServices.IEnumerableType.IsAssignableFrom(valueType))
+ else if (GenerationServices.s_iEnumerableType.IsAssignableFrom(valueType))
{
// NOTE : strings and dictionaries are also enumerables, but we have already handled those
ilGenerator.LoadEnumerable((IEnumerable)rawValue);
}
else if (
- (valueType == GenerationServices.CharType) ||
- (valueType == GenerationServices.BooleanType) ||
- (valueType == GenerationServices.ByteType) ||
- (valueType == GenerationServices.SByteType) ||
- (valueType == GenerationServices.Int16Type) ||
- (valueType == GenerationServices.UInt16Type) ||
- (valueType == GenerationServices.Int32Type)
+ (valueType == GenerationServices.s_charType) ||
+ (valueType == GenerationServices.s_booleanType) ||
+ (valueType == GenerationServices.s_byteType) ||
+ (valueType == GenerationServices.s_sByteType) ||
+ (valueType == GenerationServices.s_int16Type) ||
+ (valueType == GenerationServices.s_uInt16Type) ||
+ (valueType == GenerationServices.s_int32Type)
)
{
// NOTE : Everything that is 32 bit or less uses ldc.i4. We need to pass int32, even if the actual types is shorter - this is IL memory model
// We have a special case for that next
ilGenerator.LoadInt((int)Convert.ChangeType(rawValue, typeof(int), CultureInfo.InvariantCulture));
}
- else if (valueType == GenerationServices.UInt32Type)
+ else if (valueType == GenerationServices.s_uInt32Type)
{
// NOTE : This one is a bit tricky. Ldc.I4 takes an Int32 as an argument, although it really treats it as a 32bit number
// That said, some UInt32 values are larger that Int32.MaxValue, so the Convert call above will fail, which is why
// we need to treat this case individually and cast to uint, and then - unchecked - to int.
ilGenerator.LoadInt(unchecked((int)((uint)rawValue)));
}
- else if (valueType == GenerationServices.Int64Type)
+ else if (valueType == GenerationServices.s_int64Type)
{
ilGenerator.LoadLong((long)rawValue);
}
- else if (valueType == GenerationServices.UInt64Type)
+ else if (valueType == GenerationServices.s_uInt64Type)
{
// NOTE : This one is a bit tricky. Ldc.I8 takes an Int64 as an argument, although it really treats it as a 64bit number
// That said, some UInt64 values are larger that Int64.MaxValue, so the direct case we use above (or Convert, for that matter)will fail, which is why
// we need to treat this case individually and cast to ulong, and then - unchecked - to long.
ilGenerator.LoadLong(unchecked((long)((ulong)rawValue)));
}
- else if (valueType == GenerationServices.SingleType)
+ else if (valueType == GenerationServices.s_singleType)
{
ilGenerator.LoadFloat((float)rawValue);
}
- else if (valueType == GenerationServices.DoubleType)
+ else if (valueType == GenerationServices.s_doubleType)
{
ilGenerator.LoadDouble((double)rawValue);
}
}
// We load enumerable as an array - this is the most compact and efficient way of representing it
- Type elementType = null;
- Type closedType = null;
- if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.IEnumerableTypeofT, out closedType))
+ Type elementType;
+ if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.s_iEnumerableTypeofT, out Type? closedType))
{
elementType = closedType.GetGenericArguments()[0];
}
ilGenerator.Emit(OpCodes.Stloc, generatedArrayLocal);
int index = 0;
- foreach (object value in enumerable)
+ foreach (object? value in enumerable)
{
//
//array[<index>] = value;
ilGenerator.LoadValue(value);
if (GenerationServices.IsBoxingRequiredForValue(value) && !elementType.IsValueType)
{
- ilGenerator.Emit(OpCodes.Box, value.GetType());
+ ilGenerator.Emit(OpCodes.Box, value!.GetType());
}
ilGenerator.Emit(OpCodes.Stelem, elementType);
index++;
ilGenerator.Emit(OpCodes.Ldloc, generatedArrayLocal);
}
- private static bool IsBoxingRequiredForValue(object value)
+ private static bool IsBoxingRequiredForValue(object? value)
{
if (value == null)
{
//typeofs() translate into ldtoken and Type::GetTypeFromHandle call
ilGenerator.Emit(OpCodes.Ldtoken, type);
- ilGenerator.EmitCall(OpCodes.Call, GenerationServices._typeGetTypeFromHandleMethod, null);
+ ilGenerator.EmitCall(OpCodes.Call, GenerationServices.s_typeGetTypeFromHandleMethod, null);
}
}
}
{
internal static class ReflectionInvoke
{
- public static object SafeCreateInstance(this Type type, params object[] arguments)
+ public static object? SafeCreateInstance(this Type type, params object?[]? arguments)
{
return Activator.CreateInstance(type, arguments);
}
- public static object SafeInvoke(this ConstructorInfo constructor, params object[] arguments)
+ public static object SafeInvoke(this ConstructorInfo constructor, params object?[]? arguments)
{
return constructor.Invoke(arguments);
}
- public static object SafeInvoke(this MethodInfo method, object instance, params object[] arguments)
+ public static object? SafeInvoke(this MethodInfo method, object? instance, params object?[]? arguments)
{
return method.Invoke(instance, arguments);
}
- public static object SafeGetValue(this FieldInfo field, object instance)
+ public static object? SafeGetValue(this FieldInfo field, object? instance)
{
return field.GetValue(instance);
}
- public static void SafeSetValue(this FieldInfo field, object instance, object value)
+ public static void SafeSetValue(this FieldInfo field, object? instance, object? value)
{
field.SetValue(instance, value);
}
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics;
namespace Microsoft.Internal
{
{
public static Assembly Assembly(this MemberInfo member)
{
- Type type = member as Type;
- if (type != null)
+ if (member is Type type)
{
return type.Assembly;
}
+ Debug.Assert(member.DeclaringType != null);
return member.DeclaringType.Assembly;
}
public static bool IsVisible(this ConstructorInfo constructor)
{
- return constructor.DeclaringType.IsVisible && constructor.IsPublic;
+ return constructor.DeclaringType!.IsVisible && constructor.IsPublic;
}
public static bool IsVisible(this FieldInfo field)
{
+ Debug.Assert(field.DeclaringType != null);
return field.DeclaringType.IsVisible && field.IsPublic;
}
public static bool IsVisible(this MethodInfo method)
{
+ Debug.Assert(method.DeclaringType != null);
if (!method.DeclaringType.IsVisible)
return false;
return true;
}
- public static string GetDisplayName(Type declaringType, string name)
+ public static string GetDisplayName(Type declaringType, string? name)
{
if (declaringType == null)
{
return AttributedModelServices.GetTypeIdentity(((Type)member));
}
- return GetDisplayName(member.DeclaringType, member.Name);
+ return GetDisplayName(member.DeclaringType!, member.Name);
}
- internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, out Type targetClosedInterfaceType)
+ internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, [NotNullWhen(true)] out Type? targetClosedInterfaceType)
{
// The interface must be open
if (!targetOpenInterfaceType.IsInterface ||
// more expensive implementation of GetInterface, this does mean that we're
// takign the chance that there aren't too many types which implement multiple
// interfaces by the same name...
- Type targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false);
+ Type? targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false);
if (targetInterface != null &&
targetInterface.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType)
{
{
IEnumerable<MethodInfo> declaredMethods = type.GetDeclaredMethods();
- Type baseType = type.BaseType;
+ Type? baseType = type.BaseType;
+ Debug.Assert(baseType != null);
if (baseType.UnderlyingSystemType != typeof(object))
{
return declaredMethods.Concat(baseType.GetAllMethods());
{
IEnumerable<FieldInfo> declaredFields = type.GetDeclaredFields();
- Type baseType = type.BaseType;
+ Type? baseType = type.BaseType;
+ Debug.Assert(baseType != null);
if (baseType.UnderlyingSystemType != typeof(object))
{
return declaredFields.Concat(baseType.GetAllFields());
}
}
- internal static bool HasBaseclassOf(this Type type, Type baseClass)
+ internal static bool HasBaseclassOf(this Type? type, Type baseClass)
{
if (type == baseClass)
{
}
[DebuggerStepThrough]
- public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName)
+ public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>>? values, string parameterName)
where TKey : class
where TValue : class
{
}
[DebuggerStepThrough]
- public static void NullOrNotNullElements<T>(IEnumerable<T> values, string parameterName)
+ public static void NullOrNotNullElements<T>(IEnumerable<T>? values, string parameterName)
where T : class
{
NotNullElements(values, parameterName);
}
[DebuggerStepThrough]
- private static void NotNullElements<T>(IEnumerable<T> values, string parameterName)
+ private static void NotNullElements<T>(IEnumerable<T>? values, string parameterName)
where T : class
{
if (values != null)
}
[DebuggerStepThrough]
- public static void NullOrNotNullElements<T>(T[] values, string parameterName)
+ public static void NullOrNotNullElements<T>(T[]? values, string parameterName)
where T : class
{
NotNullElements(values, parameterName);
}
[DebuggerStepThrough]
- private static void NotNullElements<T>(T[] values, string parameterName)
+ private static void NotNullElements<T>(T[]? values, string parameterName)
where T : class
{
if (values != null)
}
[DebuggerStepThrough]
- private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName)
+ private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>>? values, string parameterName)
where TKey : class
where TValue : class
{
<NoWarn>$(NoWarn);CS1573</NoWarn>
<GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetsNetStandard)' == 'true'">SR.PlatformNotSupported_ComponentModel_Composition</GeneratePlatformNotSupportedAssemblyMessage>
<Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;netcoreapp2.0-Debug;netcoreapp2.0-Release;netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+ <Nullable>enable</Nullable>
+ <NoWarn Condition="'$(TargetsNetCoreApp)' != 'true' or '$(TargetFramework)' == 'netcoreapp2.0'">$(NoWarn);nullable</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Include="TypeForwards.cs" />
private readonly AttributedPartCreationInfo _partCreationInfo;
private readonly MemberInfo _member;
private readonly ExportAttribute _exportAttribute;
- private readonly Type _typeIdentityType;
+ private readonly Type? _typeIdentityType;
- private IDictionary<string, object> _metadata;
+ private IDictionary<string, object?>? _metadata;
- public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type typeIdentityType, string contractName)
- : base(contractName, (IDictionary<string, object>)null)
+ public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type? typeIdentityType, string contractName)
+ : base(contractName, (IDictionary<string, object?>?)null)
{
if (partCreationInfo == null)
{
_typeIdentityType = typeIdentityType;
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
if (_metadata == null)
{
- IDictionary<string, object> metadata;
- _member.TryExportMetadataForMember(out metadata);
+ _member.TryExportMetadataForMember(out IDictionary<string, object?> metadata);
string typeIdentity = _exportAttribute.IsContractNameSameAsTypeIdentity() ?
ContractName :
{
internal static class AttributedModelDiscovery
{
- public static ComposablePartDefinition CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement origin)
+ public static ComposablePartDefinition? CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement? origin)
{
AttributedPartCreationInfo creationInfo = new AttributedPartCreationInfo(type, null, false, origin);
if (!creationInfo.IsPartDiscoverable())
return new ReflectionComposablePartDefinition(creationInfo);
}
- public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin)
+ public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin)
{
if (type == null)
{
}
// If given an instance then we want to pass the default composition options because we treat it as a shared part
- ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null);
+ ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement?)null);
return new ReflectionComposablePart(definition, attributedPart);
}
throw new ArgumentException(SR.Format(SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext));
}
- ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(mappedType, PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null);
+ ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(mappedType, PartCreationPolicyAttribute.Shared, true, (ICompositionElement?)null);
return CreatePart(definition, attributedPart);
}
{
private readonly Type _type;
private readonly bool _ignoreConstructorImports = false;
- private readonly ICompositionElement _origin;
- private PartCreationPolicyAttribute _partCreationPolicy = null;
- private ConstructorInfo _constructor;
- private IEnumerable<ExportDefinition> _exports;
- private IEnumerable<ImportDefinition> _imports;
- private HashSet<string> _contractNamesOnNonInterfaces;
-
- public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin)
+ private readonly ICompositionElement? _origin;
+ private PartCreationPolicyAttribute? _partCreationPolicy = null;
+ private ConstructorInfo? _constructor;
+ private IEnumerable<ExportDefinition>? _exports;
+ private IEnumerable<ImportDefinition>? _imports;
+ private HashSet<string>? _contractNamesOnNonInterfaces;
+
+ public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin)
{
if (type == null)
{
return new Lazy<Type>(GetPartType, LazyThreadSafetyMode.PublicationOnly);
}
- public ConstructorInfo GetConstructor()
+ public ConstructorInfo? GetConstructor()
{
if (_constructor == null && !_ignoreConstructorImports)
{
return _constructor;
}
- public IDictionary<string, object> GetMetadata()
+ public IDictionary<string, object?> GetMetadata()
{
return _type.GetPartMetadataForType(CreationPolicy);
}
public IEnumerable<ExportDefinition> GetExports()
{
DiscoverExportsAndImports();
- return _exports;
+ return _exports!;
}
public IEnumerable<ImportDefinition> GetImports()
{
DiscoverExportsAndImports();
- return _imports;
+ return _imports!;
}
public bool IsDisposalRequired
get { return GetDisplayName(); }
}
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return _origin; }
}
}
}
- private static ConstructorInfo SelectPartConstructor(Type type)
+ private static ConstructorInfo? SelectPartConstructor(Type type)
{
if (type == null)
{
}
// Select the marked constructor if there is exactly one marked
- ConstructorInfo importingConstructor = null;
- ConstructorInfo defaultConstructor = null;
+ ConstructorInfo? importingConstructor = null;
+ ConstructorInfo? defaultConstructor = null;
foreach (ConstructorInfo constructor in constructors)
{
// an importing constructor found
private AttributedExportDefinition CreateExportDefinition(MemberInfo member, ExportAttribute exportAttribute)
{
- string contractName = null;
- Type typeIdentityType = null;
- member.GetContractInfoFromExport(exportAttribute, out typeIdentityType, out contractName);
+ member.GetContractInfoFromExport(exportAttribute, out Type? typeIdentityType, out string contractName);
return new AttributedExportDefinition(this, member, exportAttribute, typeIdentityType, contractName);
}
// in the hiearchy from most derived to the lowest base type, followed
// by all the interfaces that this type implements.
- Type currentType = type.BaseType;
+ Type? currentType = type.BaseType;
if (currentType == null)
{
imports.Add(importDefinition);
}
- ConstructorInfo constructor = GetConstructor();
+ ConstructorInfo? constructor = GetConstructor();
if (constructor != null)
{
// Walk up the type chain until you hit object.
if (type.BaseType != null)
{
- Type baseType = type.BaseType;
+ Type? baseType = type.BaseType;
// Stopping at object instead of null to help with performance. It is a noticable performance
// gain (~5%) if we don't have to try and pull the attributes we know don't exist on object.
public static class AttributedModelServices
{
[SuppressMessage("Microsoft.Design", "CA1004")]
- public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
+ public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object?> metadata)
{
Requires.NotNull(metadata, nameof(metadata));
return AttributedModelDiscovery.CreatePart(reflectionComposablePartDefinition, attributedPart);
}
- public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin)
+ public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement? origin)
{
Requires.NotNull(type, nameof(type));
return AttributedModelServices.CreatePartDefinition(type, origin, false);
}
- public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable)
+ public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement? origin, bool ensureIsDiscoverable)
{
Requires.NotNull(type, nameof(type));
if (ensureIsDiscoverable)
{
- return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin);
+ return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin)!;
}
else
{
string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T));
- IDictionary<string, object> metadata = new Dictionary<string, object>();
+ IDictionary<string, object?> metadata = new Dictionary<string, object?>();
metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);
return batch.AddExport(new Export(contractName, metadata, () => exportedValue));
throw new ArgumentNullException(nameof(_reflectionContextType));
}
- ReflectionContext reflectionContext = null;
+ ReflectionContext reflectionContext;
try
{
- reflectionContext = (ReflectionContext)Activator.CreateInstance(_reflectionContextType);
+ reflectionContext = (ReflectionContext)Activator.CreateInstance(_reflectionContextType)!;
}
catch (InvalidCastException invalidCastException)
{
/// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
/// </summary>
public ChangeRejectedException()
- : this((string)null, (Exception)null)
+ : this((string?)null, (Exception?)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
/// </summary>
- public ChangeRejectedException(string message)
- : this(message, (Exception)null)
+ public ChangeRejectedException(string? message)
+ : this(message, (Exception?)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
/// </summary>
- public ChangeRejectedException(string message, Exception innerException)
- : base(message, innerException, (IEnumerable<CompositionError>)null)
+ public ChangeRejectedException(string? message, Exception? innerException)
+ : base(message, innerException, (IEnumerable<CompositionError>?)null)
{
}
/// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
/// </summary>
/// <param name="errors">List of errors that occured while applying the changes.</param>
- public ChangeRejectedException(IEnumerable<CompositionError> errors)
- : base((string)null, (Exception)null, errors)
+ public ChangeRejectedException(IEnumerable<CompositionError>? errors)
+ : base((string?)null, (Exception?)null, errors)
{
}
/// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class.
/// </summary>
public CompositionContractMismatchException()
- : this((string)null, (Exception)null)
+ : this((string?)null, (Exception?)null)
{
}
/// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.Message"/> property to its default value.
/// </param>
- public CompositionContractMismatchException(string message)
- : this(message, (Exception)null)
+ public CompositionContractMismatchException(string? message)
+ : this(message, (Exception?)null)
{
}
/// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
/// </param>
- public CompositionContractMismatchException(string message, Exception innerException)
+ public CompositionContractMismatchException(string? message, Exception? innerException)
: base(message, innerException)
{
}
{
private readonly CompositionErrorId _id;
private readonly string _description;
- private readonly Exception _exception;
+ private readonly Exception? _exception;
- private readonly ICompositionElement _element;
+ private readonly ICompositionElement? _element;
/// <summary>
/// Initializes a new instance of the <see cref="CompositionError"/> class
/// <see cref="CompositionError"/>; or <see langword="null"/> to set the
/// <see cref="Description"/> property to an empty string ("").
/// </param>
- public CompositionError(string message)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, (Exception)null)
+ public CompositionError(string? message)
+ : this(CompositionErrorId.Unknown, message, (ICompositionElement?)null, (Exception?)null)
{
}
/// <see cref="CompositionError"/>; or <see langword="null"/> to set the
/// <see cref="Description"/> property to an empty string ("").
/// </param>
- public CompositionError(string message, ICompositionElement element)
- : this(CompositionErrorId.Unknown, message, element, (Exception)null)
+ public CompositionError(string? message, ICompositionElement? element)
+ : this(CompositionErrorId.Unknown, message, element, (Exception?)null)
{
}
/// <see cref="CompositionError"/>; or <see langword="null"/> to set
/// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
/// </param>
- public CompositionError(string message, Exception exception)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, exception)
+ public CompositionError(string? message, Exception? exception)
+ : this(CompositionErrorId.Unknown, message, (ICompositionElement?)null, exception)
{
}
/// <see cref="CompositionError"/>; or <see langword="null"/> to set
/// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
/// </param>
- public CompositionError(string message, ICompositionElement element, Exception exception)
+ public CompositionError(string? message, ICompositionElement? element, Exception? exception)
: this(CompositionErrorId.Unknown, message, element, exception)
{
}
- internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception)
+ internal CompositionError(CompositionErrorId id, string? description, ICompositionElement? element, Exception? exception)
{
_id = id;
_description = description ?? string.Empty;
/// The <see cref="ICompositionElement"/> that is the cause of the
/// <see cref="CompositionError"/>. The default is <see langword="null"/>.
/// </value>
- public ICompositionElement Element
+ public ICompositionElement? Element
{
get { return _element; }
}
/// The <see cref="Exception"/> that is the underlying cause of the
/// <see cref="CompositionError"/>. The default is <see langword="null"/>.
/// </value>
- public Exception Exception
+ public Exception? Exception
{
get { return _exception; }
}
get { return _id; }
}
- internal Exception InnerException
+ internal Exception? InnerException
{
get { return Exception; }
}
return Description;
}
- internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters)
+ internal static CompositionError Create(CompositionErrorId id, string format, params object?[] parameters)
{
- return Create(id, (ICompositionElement)null, (Exception)null, format, parameters);
+ return Create(id, (ICompositionElement?)null, (Exception?)null, format, parameters);
}
- internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters)
+ internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object?[] parameters)
{
- return Create(id, element, (Exception)null, format, parameters);
+ return Create(id, element, (Exception?)null, format, parameters);
}
- internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters)
+ internal static CompositionError Create(CompositionErrorId id, ICompositionElement? element, Exception? exception, string format, params object?[] parameters)
{
return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception);
}
get { return _error.Description; }
}
- public Exception Exception
+ public Exception? Exception
{
get { return _error.Exception; }
}
- public ICompositionElement Element
+ public ICompositionElement? Element
{
get { return _error.Element; }
}
/// Initializes a new instance of the <see cref="CompositionException"/> class.
/// </summary>
public CompositionException()
- : this((string)null, (Exception)null, (IEnumerable<CompositionError>)null)
+ : this((string?)null, (Exception?)null, (IEnumerable<CompositionError>?)null)
{
}
/// <see cref="CompositionException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.Message"/> property to its default value.
/// </param>
- public CompositionException(string message)
- : this(message, (Exception)null, (IEnumerable<CompositionError>)null)
+ public CompositionException(string? message)
+ : this(message, (Exception?)null, (IEnumerable<CompositionError>?)null)
{
}
/// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
/// </param>
- public CompositionException(string message, Exception innerException)
- : this(message, innerException, (IEnumerable<CompositionError>)null)
+ public CompositionException(string? message, Exception? innerException)
+ : this(message, innerException, (IEnumerable<CompositionError>?)null)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="errors"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionException(IEnumerable<CompositionError> errors)
- : this((string)null, (Exception)null, errors)
+ public CompositionException(IEnumerable<CompositionError>? errors)
+ : this((string?)null, (Exception?)null, errors)
{
}
- internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
+ internal CompositionException(string? message, Exception? innerException, IEnumerable<CompositionError>? errors)
: base(message, innerException)
{
Requires.NullOrNotNullElements(errors, nameof(errors));
{
if (error.Exception != null)
{
- var ce = error.Exception as CompositionException;
- if (ce != null)
+ if (error.Exception is CompositionException ce)
{
if (ce.RootCauses.Count > 0)
{
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName);
- while ((element = element.Origin) != null)
+ while ((element = element.Origin!) != null)
{
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName);
}
private static void VisitException(Exception exception, VisitContext context)
{
- CompositionException composition = exception as CompositionException;
- if (composition != null)
+ if (exception is CompositionException composition)
{
VisitCompositionException(composition, context);
}
internal struct CompositionResult
{
public static readonly CompositionResult SucceededResult;
- private readonly IEnumerable<CompositionError> _errors;
+ private readonly IEnumerable<CompositionError>? _errors;
public CompositionResult(params CompositionError[] errors)
: this((IEnumerable<CompositionError>)errors)
{
}
- public CompositionResult(IEnumerable<CompositionError> errors)
+ public CompositionResult(IEnumerable<CompositionError>? errors)
{
_errors = errors;
}
return MergeErrors(new CompositionError[] { error });
}
- public CompositionResult MergeErrors(IEnumerable<CompositionError> errors)
+ public CompositionResult MergeErrors(IEnumerable<CompositionError>? errors)
{
return new CompositionResult(_errors.ConcatAllowingNull(errors));
}
ThrowOnErrors(null);
}
- public void ThrowOnErrors(AtomicComposition atomicComposition)
+ public void ThrowOnErrors(AtomicComposition? atomicComposition)
{
if (!Succeeded)
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.Internal.Collections;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition
{
internal struct CompositionResult<T>
{
- private readonly IEnumerable<CompositionError> _errors;
- private readonly T _value;
+ private readonly IEnumerable<CompositionError>? _errors;
+ [AllowNull] private readonly T _value;
public CompositionResult(T value)
: this(value, null)
{
}
- public CompositionResult(IEnumerable<CompositionError> errors)
+ public CompositionResult(IEnumerable<CompositionError>? errors)
: this(default, errors)
{
}
- internal CompositionResult(T value, IEnumerable<CompositionError> errors)
+ internal CompositionResult([AllowNull] T value, IEnumerable<CompositionError>? errors)
{
_errors = errors;
_value = value;
{
// NOTE : these are here as Reflection member search is pretty expensive, and we want that to be done once.
// Also, making these static would cause this class to fail loading if we rename members of ExportDefinition.
- private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName");
- private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata");
- private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey");
- private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item");
- private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[] { typeof(object) });
- private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType");
-
- public static Expression<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, CreationPolicy requiredCreationPolicy)
+ private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName")!;
+ private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata")!;
+ private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey")!;
+ private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item")!;
+ private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[] { typeof(object) })!;
+ private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType")!;
+
+ public static Expression<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, CreationPolicy requiredCreationPolicy)
{
ParameterExpression parameter = Expression.Parameter(typeof(ExportDefinition), "exportDefinition");
if (requiredMetadata != null)
{
- Expression metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter);
+ Expression? metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter);
if (metadataConstraintBody != null)
{
constraintBody = Expression.AndAlso(constraintBody, metadataConstraintBody);
Expression.Constant(contractName ?? string.Empty, typeof(string)));
}
- private static Expression CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter)
+ private static Expression? CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter)
{
if (requiredMetadata == null)
{
throw new ArgumentNullException(nameof(parameter));
}
- Expression body = null;
+ Expression? body = null;
foreach (KeyValuePair<string, Type> requiredMetadataItem in requiredMetadata)
{
// export.Metadata.ContainsKey(<metadataItem>)
private const char GenericFormatClosingBracket = '}';
[ThreadStatic]
- private static Dictionary<Type, string> typeIdentityCache;
+ private static Dictionary<Type, string>? typeIdentityCache;
private static Dictionary<Type, string> TypeIdentityCache
{
throw new ArgumentNullException(nameof(type));
}
- string typeIdentity = null;
-
- if (!TypeIdentityCache.TryGetValue(type, out typeIdentity))
+ if (!TypeIdentityCache.TryGetValue(type, out string? typeIdentity))
{
if (!type.IsAbstract && type.HasBaseclassOf(typeof(Delegate)))
{
- MethodInfo method = type.GetMethod("Invoke");
+ MethodInfo method = type.GetMethod("Invoke")!;
typeIdentity = ContractNameServices.GetTypeIdentityFromMethod(method);
}
else if (type.IsGenericParameter)
//
Type rootElementType = FindArrayElementType(type);
WriteType(typeName, rootElementType, formatGenericName);
- Type elementType = type;
+ Type? elementType = type;
do
{
WriteArrayTypeDimensions(typeName, elementType);
//
// Writes pointer type e.g <TypeName>*
//
- WriteType(typeName, type.GetElementType(), formatGenericName);
+ WriteType(typeName, type.GetElementType()!, formatGenericName);
typeName.Append(PointerSymbol);
}
//
// Writes by ref type e.g <TypeName>&
//
- WriteType(typeName, type.GetElementType(), formatGenericName);
+ WriteType(typeName, type.GetElementType()!, formatGenericName);
typeName.Append(ReferenceSymbol);
}
//
// Gets array element type by calling GetElementType() until the element is not an array
//
- Type elementType = type;
+ Type? elementType = type;
while ((elementType = elementType.GetElementType()) != null && elementType.IsArray) { }
- return elementType;
+ return elementType!;
}
private static string FindGenericTypeName(string genericName)
CompositionErrorId.ImportEngine_ImportCardinalityMismatch,
exception.Message,
definition.ToElement(),
- (Exception)null);
+ (Exception?)null);
}
public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException)
/// </para>
/// </remarks>
public ExportAttribute()
- : this((string)null, (Type)null)
+ : this((string?)null, (Type?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ExportAttribute(Type contractType)
- : this((string)null, contractType)
+ public ExportAttribute(Type? contractType)
+ : this((string?)null, contractType)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ExportAttribute(string contractName)
- : this(contractName, (Type)null)
+ public ExportAttribute(string? contractName)
+ : this(contractName, (Type?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ExportAttribute(string contractName, Type contractType)
+ public ExportAttribute(string? contractName, Type? contractType)
{
ContractName = contractName;
ContractType = contractType;
/// A <see cref="string"/> containing the contract name to export the type or member
/// marked with this attribute, under. The default value is an empty string ("").
/// </value>
- public string ContractName { get; private set; }
+ public string? ContractName { get; private set; }
/// <summary>
/// Get the contract type that is exported by the member that this attribute is attached to.
/// <see langword="null"/> which means that the type will be obtained by looking at the type on
/// the member that this export is attached to.
/// </value>
- public Type ContractType { get; private set; }
+ public Type? ContractType { get; private set; }
}
}
/// An <see cref="object"/> containing the metadata value. This can be
/// <see langword="null"/>.
/// </param>
- public ExportMetadataAttribute(string name, object value)
+ public ExportMetadataAttribute(string? name, object? value)
{
Name = name ?? string.Empty;
Value = value;
/// <value>
/// An <see cref="object"/> containing the metadata value.
/// </value>
- public object Value
+ public object? Value
{
get;
private set;
// Provides helpers for creating and dealing with Exports
internal static partial class ExportServices
{
- private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.NonPublic | BindingFlags.Static);
+ private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.NonPublic | BindingFlags.Static)!;
+ private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.NonPublic | BindingFlags.Static)!;
+ private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.NonPublic | BindingFlags.Static)!;
internal static readonly Type DefaultMetadataViewType = typeof(IDictionary<string, object>);
internal static readonly Type DefaultExportedValueType = typeof(object);
Array.Empty<ParameterModifier>()) != null;
}
- internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
+ internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type? exportType, Type? metadataViewType)
{
- MethodInfo genericMethod = null;
+ MethodInfo genericMethod;
if (metadataViewType != null)
{
genericMethod = _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType, metadataViewType);
return (Func<Export, object>)Delegate.CreateDelegate(typeof(Func<Export, object>), genericMethod);
}
- internal static Func<Export, Lazy<object, object>> CreateSemiStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
+ internal static Func<Export, Lazy<object, object>> CreateSemiStronglyTypedLazyFactory(Type? exportType, Type? metadataViewType)
{
MethodInfo genericMethod = _createSemiStronglyTypedLazy.MakeGenericMethod(
exportType ?? ExportServices.DefaultExportedValueType,
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
internal static Lazy<T, M> CreateStronglyTypedLazyOfTM<T, M>(Export export)
{
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
+ if (export is IDisposable disposable)
{
return new DisposableLazy<T, M>(
() => ExportServices.GetCastedExportedValue<T>(export),
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
internal static Lazy<T> CreateStronglyTypedLazyOfT<T>(Export export)
{
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
+ if (export is IDisposable disposable)
{
return new DisposableLazy<T>(
() => ExportServices.GetCastedExportedValue<T>(export),
else
{
return new Lazy<T>(() => ExportServices.GetCastedExportedValue<T>(export), LazyThreadSafetyMode.PublicationOnly);
-
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- internal static Lazy<object, object> CreateSemiStronglyTypedLazy<T, M>(Export export)
+ internal static Lazy<object?, object> CreateSemiStronglyTypedLazy<T, M>(Export export)
{
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
+ if (export is IDisposable disposable)
{
- return new DisposableLazy<object, object>(
+ return new DisposableLazy<object?, object>(
() => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
+ AttributedModelServices.GetMetadataView<M>(export.Metadata)!,
disposable,
LazyThreadSafetyMode.PublicationOnly);
}
else
{
- return new Lazy<object, object>(
+ return new Lazy<object?, object>(
() => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
+ AttributedModelServices.GetMetadataView<M>(export.Metadata)!,
LazyThreadSafetyMode.PublicationOnly);
}
}
return CastExportedValue<T>(export.ToElement(), export.Value);
}
- internal static T CastExportedValue<T>(ICompositionElement element, object exportedValue)
+ internal static T CastExportedValue<T>(ICompositionElement element, object? exportedValue)
{
- object typedExportedValue = null;
-
- bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out typedExportedValue);
+ bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out object? typedExportedValue);
if (!succeeded)
{
throw new CompositionContractMismatchException(SR.Format(
typeof(T)));
}
- return (T)typedExportedValue;
+ return (T)typedExportedValue!;
}
- internal static ExportCardinalityCheckResult CheckCardinality<T>(ImportDefinition definition, IEnumerable<T> enumerable)
+ internal static ExportCardinalityCheckResult CheckCardinality<T>(ImportDefinition definition, IEnumerable<T>? enumerable)
{
EnumerableCardinality actualCardinality = (enumerable != null) ? enumerable.GetCardinality() : EnumerableCardinality.Zero;
/// </remarks>
public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged
{
- private readonly ComposablePartCatalogCollection _catalogs = null;
+ private readonly ComposablePartCatalogCollection _catalogs;
private volatile int _isDisposed = 0;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class.
/// </summary>
public AggregateCatalog()
- : this((IEnumerable<ComposablePartCatalog>)null)
+ : this((IEnumerable<ComposablePartCatalog>?)null)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
- public AggregateCatalog(params ComposablePartCatalog[] catalogs)
- : this((IEnumerable<ComposablePartCatalog>)catalogs)
+ public AggregateCatalog(params ComposablePartCatalog[]? catalogs)
+ : this((IEnumerable<ComposablePartCatalog>?)catalogs)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
- public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
+ public AggregateCatalog(IEnumerable<ComposablePartCatalog>? catalogs)
{
Requires.NullOrNotNullElements(catalogs, nameof(catalogs));
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed
{
add
{
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing
{
add
{
// We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases.
// We do so to avoid any unnecessary allocations
- IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> result = null;
- List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null;
+ IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? result = null;
+ List<Tuple<ComposablePartDefinition, ExportDefinition>>? aggregateResult = null;
foreach (var catalog in _catalogs)
{
/// That is, it will not try to dispose of any of them when it gets disposed.
/// </para>
/// </remarks>
- public AggregateExportProvider(params ExportProvider[] providers)
+ public AggregateExportProvider(params ExportProvider[]? providers)
{
// NOTE : we optimize for the array case here, because the collection of providers is typically tiny
// Arrays are much more compact to store and much faster to create and enumerate
- ExportProvider[] copiedProviders = null;
+ ExportProvider[]? copiedProviders = null;
if (providers != null)
{
copiedProviders = new ExportProvider[providers.Length];
/// That is, it will not try to dispose of any of them when it gets disposed.
/// </para>
/// </remarks>
- public AggregateExportProvider(IEnumerable<ExportProvider> providers)
+ public AggregateExportProvider(IEnumerable<ExportProvider>? providers)
: this((providers != null) ? providers.AsArray() : null)
{
}
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
}
else
{
- IEnumerable<Export> allExports = null;
+ IEnumerable<Export>? allExports = null;
// if asked for "one or less", the prioriry is at play - the first provider that agrees to return the value
// which best complies with the request, wins.
foreach (ExportProvider provider in _providers)
{
- IEnumerable<Export> exports;
- bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out exports);
+ bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out IEnumerable<Export>? exports);
+ Debug.Assert(exports != null);
bool anyExports = exports.FastAny();
if (cardinalityCheckResult && anyExports)
{
}
}
- return allExports;
+ return allExports!;
}
}
- private void OnExportChangedInternal(object sender, ExportsChangeEventArgs e)
+ private void OnExportChangedInternal(object? sender, ExportsChangeEventArgs e)
{
OnExportsChanged(e);
}
- private void OnExportChangingInternal(object sender, ExportsChangeEventArgs e)
+ private void OnExportChangingInternal(object? sender, ExportsChangeEventArgs e)
{
OnExportsChanging(e);
}
public partial class ApplicationCatalog : ComposablePartCatalog, ICompositionElement
{
private bool _isDisposed = false;
- private volatile AggregateCatalog _innerCatalog = null;
+ private volatile AggregateCatalog? _innerCatalog = null;
private readonly object _thisLock = new object();
- private readonly ICompositionElement _definitionOrigin = null;
- private readonly ReflectionContext _reflectionContext = null;
+ private readonly ICompositionElement? _definitionOrigin = null;
+ private readonly ReflectionContext? _reflectionContext = null;
public ApplicationCatalog() { }
catalogs.Add(CreateCatalog(location, "*.exe"));
catalogs.Add(CreateCatalog(location, "*.dll"));
- string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
+ string? relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
if (!string.IsNullOrEmpty(relativeSearchPath))
{
string[] probingPaths = relativeSearchPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
{
if (!_isDisposed)
{
- IDisposable innerCatalog = null;
+ IDisposable? innerCatalog = null;
lock (_thisLock)
{
innerCatalog = _innerCatalog as IDisposable;
/// This property always returns <see langword="null"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return null; }
}
{
private readonly object _thisLock = new object();
private readonly ICompositionElement _definitionOrigin;
- private volatile Assembly _assembly = null;
- private volatile ComposablePartCatalog _innerCatalog = null;
+ private volatile Assembly _assembly = null!; // Always initiialized with helper
+ private volatile ComposablePartCatalog? _innerCatalog = null;
private int _isDisposed = 0;
- private readonly ReflectionContext _reflectionContext = default(ReflectionContext);
+ private readonly ReflectionContext? _reflectionContext = default(ReflectionContext);
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyCatalog"/> class
/// This property always returns <see langword="null"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return null; }
}
/// </summary>
public class AtomicComposition : IDisposable
{
- private readonly AtomicComposition _outerAtomicComposition;
- private KeyValuePair<object, object>[] _values;
+ private readonly AtomicComposition? _outerAtomicComposition;
+ private KeyValuePair<object, object?>[]? _values;
private int _valueCount = 0;
- private List<Action> _completeActionList;
- private List<Action> _revertActionList;
+ private List<Action>? _completeActionList;
+ private List<Action>? _revertActionList;
private bool _isDisposed = false;
private bool _isCompleted = false;
private bool _containsInnerAtomicComposition = false;
{
}
- public AtomicComposition(AtomicComposition outerAtomicComposition)
+ public AtomicComposition(AtomicComposition? outerAtomicComposition)
{
// Lock the inner atomicComposition so that we can assume nothing changes except on
// the innermost scope, and thereby optimize the query path
}
}
- public void SetValue(object key, object value)
+ public void SetValue(object key, object? value)
{
ThrowIfDisposed();
ThrowIfCompleted();
SetValueInternal(key, value);
}
- public bool TryGetValue<T>(object key, out T value)
+ public bool TryGetValue<T>(object key, [MaybeNullWhen(false)] out T value)
{
return TryGetValue(key, false, out value);
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
- public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value)
+ public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value)
{
ThrowIfDisposed();
ThrowIfCompleted();
{
if (_revertActionList != null)
{
- List<Exception> exceptions = null;
+ List<Exception>? exceptions = null;
// Execute the revert actions in reverse order to ensure
// everything incrementally rollsback its state.
// Completeting the outer most scope is easy, just execute all the actions
if (_completeActionList != null)
{
- List<Exception> exceptions = null;
+ List<Exception>? exceptions = null;
foreach (Action action in _completeActionList)
{
for (var index = 0; index < _valueCount; index++)
{
_outerAtomicComposition.SetValueInternal(
- _values[index].Key, _values[index].Value);
+ _values![index].Key, _values[index].Value);
}
}
}
}
- private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, out T value)
+ private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value)
{
for (var index = 0; index < _valueCount; index++)
{
- if (_values[index].Key == key)
+ if (_values![index].Key == key)
{
- value = (T)_values[index].Value;
+ value = (T)_values[index].Value!;
return true;
}
}
return _outerAtomicComposition.TryGetValueInternal<T>(key, localAtomicCompositionOnly, out value);
}
- value = default(T);
+ value = default(T)!;
return false;
}
- private void SetValueInternal(object key, object value)
+ private void SetValueInternal(object key, object? value)
{
// Handle overwrites quickly
for (var index = 0; index < _valueCount; index++)
{
- if (_values[index].Key == key)
+ if (_values![index].Key == key)
{
- _values[index] = new KeyValuePair<object, object>(key, value);
+ _values[index] = new KeyValuePair<object, object?>(key, value);
return;
}
}
// Expand storage when needed
if (_values == null || _valueCount == _values.Length)
{
- var newQueries = new KeyValuePair<object, object>[_valueCount == 0 ? 5 : _valueCount * 2];
+ var newQueries = new KeyValuePair<object, object?>[_valueCount == 0 ? 5 : _valueCount * 2];
if (_values != null)
{
Array.Copy(_values, newQueries, _valueCount);
}
// Store a new entry
- _values[_valueCount] = new KeyValuePair<object, object>(key, value);
+ _values[_valueCount] = new KeyValuePair<object, object?>(key, value);
_valueCount++;
return;
}
{
internal static class AtomicCompositionExtensions
{
- internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, T defaultResultAndKey) where T : class
+ internal static T GetValueAllowNull<T>(this AtomicComposition? atomicComposition, T defaultResultAndKey) where T : class
{
if (defaultResultAndKey == null)
{
return GetValueAllowNull<T>(atomicComposition, defaultResultAndKey, defaultResultAndKey);
}
- internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, object key, T defaultResult)
+ internal static T GetValueAllowNull<T>(this AtomicComposition? atomicComposition, object key, T defaultResult)
{
T result;
if (atomicComposition != null && atomicComposition.TryGetValue(key, out result))
return defaultResult;
}
- internal static void AddRevertActionAllowNull(this AtomicComposition atomicComposition, Action action)
+ internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComposition, Action action)
{
if (action == null)
{
}
}
- internal static void AddCompleteActionAllowNull(this AtomicComposition atomicComposition, Action action)
+ internal static void AddCompleteActionAllowNull(this AtomicComposition? atomicComposition, Action action)
{
if (action == null)
{
return _catalogExportProvider.GetComposablePart(_partDefinition, IsSharedPart);
}
- protected void DisposePartCore(CatalogPart part, object value)
+ protected void DisposePartCore(CatalogPart part, object? value)
{
_catalogExportProvider.DisposePart(value, part, null);
}
return GetPartCore();
}
- protected override object GetExportedValueCore()
+ protected override object? GetExportedValueCore()
{
return _catalogExportProvider.GetExportedValue(GetPart(), _definition, IsSharedPart);
}
private sealed class NonSharedCatalogExport : CatalogExport, IDisposable
{
- private CatalogPart _part;
+ private CatalogPart? _part;
private readonly object _lock = new object();
public NonSharedCatalogExport(CatalogExportProvider catalogExportProvider,
// we need to ensure that the part gets created only once, as the export contract requires that the same value be returned on subsequent calls
if (_part == null)
{
- CatalogPart part = GetPartCore();
+ CatalogPart? part = GetPartCore();
lock (_lock)
{
private readonly ComposablePartDefinition _partDefinition;
private readonly ExportDefinition _exportDefinition;
private readonly ExportDefinition _factoryExportDefinition;
- private FactoryExportPartDefinition _factoryExportPartDefinition;
+ private FactoryExportPartDefinition? _factoryExportPartDefinition;
public FactoryExport(ComposablePartDefinition partDefinition, ExportDefinition exportDefinition)
{
get { return _definition.ImportDefinitions; }
}
- public override object GetExportedValue(ExportDefinition definition)
+ public override object? GetExportedValue(ExportDefinition definition)
{
if (definition != _definition.FactoryExportDefinition)
{
public void Dispose()
{
- IDisposable disposable = _export as IDisposable;
-
- if (disposable != null)
+ if (_export is IDisposable disposable)
{
disposable.Dispose();
}
using System.ComponentModel.Composition.Primitives;
using System.Threading;
+using System.Diagnostics;
namespace System.ComponentModel.Composition.Hosting
{
private sealed class ScopeCatalogExport : Export, IDisposable
{
private readonly ScopeFactoryExport _scopeFactoryExport;
- private CompositionContainer _childContainer;
- private Export _export;
+ private CompositionContainer? _childContainer;
+ private Export? _export;
private readonly object _lock = new object();
public ScopeCatalogExport(ScopeFactoryExport scopeFactoryExport)
}
}
- protected override object GetExportedValueCore()
+ protected override object? GetExportedValueCore()
{
if (_export == null)
{
- var childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog);
+ CompositionContainer? childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog);
- var export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any);
+ Debug.Assert(childContainer.CatalogExportProvider != null);
+ Export? export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any);
lock (_lock)
{
if (_export == null)
public void Dispose()
{
- CompositionContainer childContainer = null;
- Export export = null;
+ CompositionContainer? childContainer = null;
+ Export? export = null;
if (_export != null)
{
_catalogExportProvider = catalogExportProvider;
}
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
List<Export> exports = new List<Export>();
- ImportDefinition queryImport = TranslateImport(definition);
+ ImportDefinition? queryImport = TranslateImport(definition);
if (queryImport == null)
{
return exports;
// the RevertActions need to operate before we Dispose the child container
using (var localAtomicComposition = new AtomicComposition(atomicComposition))
{
- isChildPartRejected = container.CatalogExportProvider.DetermineRejection(partDefinitionAndExportDefinition.Item1, localAtomicComposition);
+ isChildPartRejected = container.CatalogExportProvider!.DetermineRejection(partDefinitionAndExportDefinition.Item1, localAtomicComposition);
}
}
}
internal CompositionContainer CreateChildContainer(ComposablePartCatalog childCatalog)
{
- return new CompositionContainer(childCatalog, _catalogExportProvider._compositionOptions, _catalogExportProvider._sourceProvider);
+ return new CompositionContainer(childCatalog, _catalogExportProvider._compositionOptions, _catalogExportProvider._sourceProvider!);
}
- private static ImportDefinition TranslateImport(ImportDefinition definition)
+ private static ImportDefinition? TranslateImport(ImportDefinition definition)
{
- IPartCreatorImportDefinition factoryDefinition = definition as IPartCreatorImportDefinition;
+ IPartCreatorImportDefinition? factoryDefinition = definition as IPartCreatorImportDefinition;
if (factoryDefinition == null)
{
return null;
// We will always create a new child CatalogEP to satsify the request, so from the perspecitive of the caller, the policy should
// always be NonShared (or Any). From teh perspective of the callee, it's the otehr way around.
ContractBasedImportDefinition productImportDefinition = factoryDefinition.ProductImportDefinition;
- ImportDefinition result = null;
+ ImportDefinition? result = null;
switch (productImportDefinition.RequiredCreationPolicy)
{
_outerExportProvider = outerExportProvider;
}
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
return _outerExportProvider.InternalGetExportsCore(definition, atomicComposition);
}
private readonly CompositionLock _lock;
private readonly Dictionary<ComposablePartDefinition, CatalogPart> _activatedParts = new Dictionary<ComposablePartDefinition, CatalogPart>();
private readonly HashSet<ComposablePartDefinition> _rejectedParts = new HashSet<ComposablePartDefinition>();
- private ConditionalWeakTable<object, List<ComposablePart>> _gcRoots;
+ private ConditionalWeakTable<object, List<ComposablePart>>? _gcRoots;
private readonly HashSet<IDisposable> _partsToDispose = new HashSet<IDisposable>();
private ComposablePartCatalog _catalog;
private volatile bool _isDisposed = false;
private volatile bool _isRunning = false;
private readonly bool _disableSilentRejection = false;
- private ExportProvider _sourceProvider;
- private ImportEngine _importEngine;
+ private ExportProvider? _sourceProvider;
+ private ImportEngine? _importEngine;
private readonly CompositionOptions _compositionOptions;
- private ExportProvider _innerExportProvider;
+ private ExportProvider? _innerExportProvider;
/// <summary>
/// Initializes a new instance of the <see cref="CatalogExportProvider"/> class.
_catalog = catalog;
_compositionOptions = compositionOptions;
- var notifyCatalogChanged = _catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalogChanged != null)
+ if (_catalog is INotifyComposablePartCatalogChanged notifyCatalogChanged)
{
notifyCatalogChanged.Changing += OnCatalogChanging;
}
- CompositionScopeDefinition scopeDefinition = _catalog as CompositionScopeDefinition;
- if (scopeDefinition != null)
+ if (_catalog is CompositionScopeDefinition scopeDefinition)
{
_innerExportProvider = new AggregateExportProvider(new ScopeManager(this, scopeDefinition), new InnerCatalogExportProvider(this));
}
/// <see cref="CatalogExportProvider"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")]
- public ExportProvider SourceProvider
+ [DisallowNull]
+ public ExportProvider? SourceProvider
{
get
{
{
ThrowIfDisposed();
- Requires.NotNull(value, nameof(value));
+ Requires.NotNull(value!, nameof(value));
- ImportEngine newImportEngine = null;
- AggregateExportProvider aggregateExportProvider = null;
- ExportProvider sourceProvider = value;
+ ImportEngine? newImportEngine = null;
+ AggregateExportProvider? aggregateExportProvider = null;
+ ExportProvider sourceProvider = value!;
bool isThrowing = true;
try
if (isThrowing)
{
sourceProvider.ExportsChanging -= OnExportsChangingInternal;
- newImportEngine.Dispose();
+ newImportEngine!.Dispose();
if (aggregateExportProvider != null)
{
aggregateExportProvider.Dispose();
{
//Note: We do not dispose _lock on dispose because DisposePart needs it to check isDisposed state
// to eliminate race conditions between it and Dispose
- INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
- HashSet<IDisposable> partsToDispose = null;
- ImportEngine importEngine = null;
- ExportProvider sourceProvider = null;
- AggregateExportProvider aggregateExportProvider = null;
+ INotifyComposablePartCatalogChanged? catalogToUnsubscribeFrom = null;
+ HashSet<IDisposable>? partsToDispose = null;
+ ImportEngine? importEngine = null;
+ ExportProvider? sourceProvider = null;
+ AggregateExportProvider? aggregateExportProvider = null;
try
{
using (_lock.LockStateForWrite())
if (!_isDisposed)
{
catalogToUnsubscribeFrom = _catalog as INotifyComposablePartCatalogChanged;
- _catalog = null;
+ _catalog = null!;
aggregateExportProvider = _innerExportProvider as AggregateExportProvider;
_innerExportProvider = null;
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- IEnumerable<Export> exports;
- _innerExportProvider.TryGetExports(definition, atomicComposition, out exports);
- return exports;
+ _innerExportProvider.TryGetExports(definition, atomicComposition, out IEnumerable<Export>? exports);
+ return exports!;
}
- private IEnumerable<Export> InternalGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ private IEnumerable<Export> InternalGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
// Use the version of the catalog appropriate to this atomicComposition
ComposablePartCatalog currentCatalog = atomicComposition.GetValueAllowNull(_catalog);
- IPartCreatorImportDefinition partCreatorDefinition = definition as IPartCreatorImportDefinition;
bool isExportFactory = false;
- if (partCreatorDefinition != null)
+ if (definition is IPartCreatorImportDefinition partCreatorDefinition)
{
definition = partCreatorDefinition.ProductImportDefinition;
isExportFactory = true;
}
}
- private void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
+ private void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e)
{
UpdateRejections(e.AddedExports.Concat(e.RemovedExports), e.AtomicComposition);
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e)
{
using (var atomicComposition = new AtomicComposition(e.AtomicComposition))
{
// fashion)
foreach (var definition in e.RemovedDefinitions)
{
- CatalogPart removedPart = null;
+ CatalogPart? removedPart = null;
bool removed = false;
using (_lock.LockStateForRead())
if (removed)
{
var capturedDefinition = definition;
- DisposePart(null, removedPart, atomicComposition);
+ DisposePart(null, removedPart!, atomicComposition);
atomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
}
}
- UpdateRejections(addedExports.ConcatAllowingNull(removedExports), atomicComposition);
+ UpdateRejections(addedExports.ConcatAllowingNull(removedExports)!, atomicComposition);
OnExportsChanging(
new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition));
ThrowIfDisposed();
EnsureRunning();
- CatalogPart catalogPart = null;
+ CatalogPart catalogPart;
if (isSharedPart)
{
ComposablePart part = partDefinition.CreatePart();
catalogPart = new CatalogPart(part);
- IDisposable disposablePart = part as IDisposable;
- if (disposablePart != null)
+ if (part is IDisposable disposablePart)
{
using (_lock.LockStateForWrite())
{
private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition)
{
- CatalogPart catalogPart = null;
+ CatalogPart? catalogPart = null;
// look up the part
using (_lock.LockStateForRead())
}
// create a part outside of the lock
- ComposablePart newPart = partDefinition.CreatePart();
- IDisposable disposableNewPart = newPart as IDisposable;
+ ComposablePart? newPart = partDefinition.CreatePart();
+ IDisposable? disposableNewPart = newPart as IDisposable;
using (_lock.LockStateForWrite())
{
return catalogPart;
}
- private object GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart)
+ private object? GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart)
{
ThrowIfDisposed();
EnsureRunning();
// if two threads satisfy imports twice, the results is the same, just the perf hit is heavier.
bool importsSatisfied = part.ImportsSatisfied;
- ImportEngine importEngine = importsSatisfied ? null : _importEngine;
+ ImportEngine? importEngine = importsSatisfied ? null : _importEngine;
- object exportedValue = CompositionServices.GetExportedValueFromComposedPart(
+ object? exportedValue = CompositionServices.GetExportedValueFromComposedPart(
importEngine, part.Part, export);
if (!importsSatisfied)
DisposePart(exportedValue, catalogPart, atomicComposition);
}
- private void DisposePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition)
+ private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicComposition? atomicComposition)
{
if (catalogPart == null)
{
if (_isDisposed)
return;
- ImportEngine importEngine = null;
+ ImportEngine? importEngine = null;
using (_lock.LockStateForWrite())
{
if (_isDisposed)
});
}
- IDisposable diposablePart = catalogPart.Part as IDisposable;
- if (diposablePart != null)
+ if (catalogPart.Part is IDisposable diposablePart)
{
atomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
- List<ComposablePart> partList;
+ List<ComposablePart>? partList;
- ConditionalWeakTable<object, List<ComposablePart>> gcRoots = _gcRoots;
+ ConditionalWeakTable<object, List<ComposablePart>>? gcRoots = _gcRoots;
if (gcRoots == null)
{
gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
}
}
- private bool IsRejected(ComposablePartDefinition definition, AtomicComposition atomicComposition)
+ private bool IsRejected(ComposablePartDefinition definition, AtomicComposition? atomicComposition)
{
// Check to see if we're currently working on the definition in question.
// Recursive queries always answer optimistically, as if the definition hasn't
return DetermineRejection(definition, atomicComposition);
}
- private bool EnsureRejection(AtomicComposition atomicComposition)
+ private bool EnsureRejection(AtomicComposition? atomicComposition)
{
return !(_disableSilentRejection && (atomicComposition == null));
}
- private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition parentAtomicComposition)
+ private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition? parentAtomicComposition)
{
- ChangeRejectedException exception = null;
+ ChangeRejectedException? exception = null;
// if there is no active atomic composition and rejection is disabled, there's no need to do any of the below
if (!EnsureRejection(parentAtomicComposition))
var newPart = definition.CreatePart();
try
{
+ Debug.Assert(_importEngine != null);
_importEngine.PreviewImports(newPart, localAtomicComposition);
// Reuse the partially-fleshed out part the next time we need a shared
if (!_activatedParts.ContainsKey(definition))
{
_activatedParts.Add(definition, new CatalogPart(newPart));
- IDisposable newDisposablePart = newPart as IDisposable;
- if (newDisposablePart != null)
+ if (newPart is IDisposable newDisposablePart)
{
_partsToDispose.Add(newDisposablePart);
}
return true;
}
- private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
+ private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition? atomicComposition)
{
using (var localAtomicComposition = new AtomicComposition(atomicComposition))
{
/// <typeparam name="T"></typeparam>
/// <param name="currentValue"></param>
[DebuggerStepThrough]
- private void EnsureCanSet<T>(T currentValue)
+ private void EnsureCanSet<T>(T? currentValue)
where T : class
{
if ((_isRunning) || (currentValue != null))
private AtomicCompositionQueryState QueryPartState(AtomicComposition atomicComposition, ComposablePartDefinition definition)
{
- PartQueryStateNode node = GetPartQueryStateNode(atomicComposition);
+ PartQueryStateNode? node = GetPartQueryStateNode(atomicComposition);
if (node == null)
{
return AtomicCompositionQueryState.Unknown;
}
}
- private PartQueryStateNode GetPartQueryStateNode(AtomicComposition atomicComposition)
+ private PartQueryStateNode? GetPartQueryStateNode(AtomicComposition atomicComposition)
{
- PartQueryStateNode node;
- atomicComposition.TryGetValue(this, out node);
+ atomicComposition.TryGetValue(this, out PartQueryStateNode? node);
return node;
}
ComposablePartDefinition part,
AtomicCompositionQueryState state)
{
- PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
+ PartQueryStateNode? previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartEqualsQueryStateNode(part, previousNode, state));
}
HashSet<ComposablePartDefinition> hashset,
AtomicCompositionQueryState state)
{
- PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
+ PartQueryStateNode? previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartInHashSetQueryStateNode(hashset, previousNode, state));
}
private abstract class PartQueryStateNode
{
- private readonly PartQueryStateNode _previousNode;
+ private readonly PartQueryStateNode? _previousNode;
private readonly AtomicCompositionQueryState _state;
- protected PartQueryStateNode(PartQueryStateNode previousNode, AtomicCompositionQueryState state)
+ protected PartQueryStateNode(PartQueryStateNode? previousNode, AtomicCompositionQueryState state)
{
_previousNode = previousNode;
_state = state;
public AtomicCompositionQueryState GetQueryState(ComposablePartDefinition definition)
{
int hashCode = definition.GetHashCode();
- PartQueryStateNode node = this;
+ PartQueryStateNode? node = this;
do
{
if (node.IsMatchingDefinition(definition, hashCode))
{
private readonly ComposablePartDefinition _part;
private readonly int _hashCode;
- public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
+ public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode? previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_part = part;
private class PartInHashSetQueryStateNode : PartQueryStateNode
{
private readonly HashSet<ComposablePartDefinition> _parts;
- public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
+ public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode? previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_parts = parts;
/// <paramref name="addedDefinitions"/> or <paramref name="removedDefinitions"/> is <see langword="null"/>.
/// </exception>
public ComposablePartCatalogChangeEventArgs(IEnumerable<ComposablePartDefinition> addedDefinitions,
- IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition atomicComposition)
+ IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition? atomicComposition)
{
Requires.NotNull(addedDefinitions, nameof(addedDefinitions));
Requires.NotNull(removedDefinitions, nameof(removedDefinitions));
/// When the value is non-null it should be used to record temporary changed state
/// and actions that will be executed when the atomicComposition is completeed.
/// </value>
- public AtomicComposition AtomicComposition { get; private set; }
+ public AtomicComposition? AtomicComposition { get; private set; }
}
}
internal class ComposablePartCatalogCollection : ICollection<ComposablePartCatalog>, INotifyComposablePartCatalogChanged, IDisposable
{
private readonly Lock _lock = new Lock();
- private readonly Action<ComposablePartCatalogChangeEventArgs> _onChanged;
- private readonly Action<ComposablePartCatalogChangeEventArgs> _onChanging;
+ private readonly Action<ComposablePartCatalogChangeEventArgs>? _onChanged;
+ private readonly Action<ComposablePartCatalogChangeEventArgs>? _onChanging;
private List<ComposablePartCatalog> _catalogs = new List<ComposablePartCatalog>();
private volatile bool _isCopyNeeded = false;
private volatile bool _isDisposed = false;
private bool _hasChanged = false;
public ComposablePartCatalogCollection(
- IEnumerable<ComposablePartCatalog> catalogs,
- Action<ComposablePartCatalogChangeEventArgs> onChanged,
- Action<ComposablePartCatalogChangeEventArgs> onChanging)
+ IEnumerable<ComposablePartCatalog>? catalogs,
+ Action<ComposablePartCatalogChangeEventArgs>? onChanged,
+ Action<ComposablePartCatalogChangeEventArgs>? onChanging)
{
catalogs = catalogs ?? Enumerable.Empty<ComposablePartCatalog>();
_catalogs = new List<ComposablePartCatalog>(catalogs);
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
public void Clear()
{
ThrowIfDisposed();
// No action is required if we are already empty
- ComposablePartCatalog[] catalogs = null;
+ ComposablePartCatalog[]? catalogs = null;
using (new ReadLock(_lock))
{
if (_catalogs.Count == 0)
if (!_isDisposed)
{
bool disposeLock = false;
- IEnumerable<ComposablePartCatalog> catalogs = null;
+ IEnumerable<ComposablePartCatalog>? catalogs = null;
try
{
using (new WriteLock(_lock))
disposeLock = true;
catalogs = _catalogs;
- _catalogs = null;
+ _catalogs = null!;
_isDisposed = true;
}
}
private void RaiseChangedEvent(
- Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions,
- Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions)
+ Lazy<IEnumerable<ComposablePartDefinition>>? addedDefinitions,
+ Lazy<IEnumerable<ComposablePartDefinition>>? removedDefinitions)
{
if (_onChanged == null || Changed == null)
{
}
private void RaiseChangingEvent(
- Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions,
- Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions,
- AtomicComposition atomicComposition)
+ Lazy<IEnumerable<ComposablePartDefinition>>? addedDefinitions,
+ Lazy<IEnumerable<ComposablePartDefinition>>? removedDefinitions,
+ AtomicComposition? atomicComposition)
{
if (_onChanging == null || Changing == null)
{
}
}
- private void OnContainedCatalogChanged(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnContainedCatalogChanged(object? sender, ComposablePartCatalogChangeEventArgs e)
{
if (_onChanged == null || Changed == null)
{
_onChanged.Invoke(e);
}
- private void OnContainedCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnContainedCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e)
{
if (_onChanging == null || Changing == null)
{
private void SubscribeToCatalogNotifications(ComposablePartCatalog catalog)
{
- INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
+ if (catalog is INotifyComposablePartCatalogChanged notifyCatalog)
{
notifyCatalog.Changed += OnContainedCatalogChanged;
notifyCatalog.Changing += OnContainedCatalogChanging;
private void UnsubscribeFromCatalogNotifications(ComposablePartCatalog catalog)
{
- INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
+ if (catalog is INotifyComposablePartCatalogChanged notifyCatalog)
{
notifyCatalog.Changed -= OnContainedCatalogChanged;
notifyCatalog.Changing -= OnContainedCatalogChanging;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading;
private List<ComposablePart> _parts = new List<ComposablePart>();
private volatile bool _isDisposed = false;
private volatile bool _isRunning = false;
- private readonly CompositionLock _lock = null;
- private ExportProvider _sourceProvider;
- private ImportEngine _importEngine;
+ private readonly CompositionLock _lock;
+ private ExportProvider? _sourceProvider;
+ private ImportEngine? _importEngine;
private volatile bool _currentlyComposing;
private readonly CompositionOptions _compositionOptions;
if (!_isDisposed)
{
bool disposeLock = false;
- ImportEngine importEngine = null;
+ ImportEngine? importEngine = null;
try
{
using (_lock.LockStateForWrite())
/// <see cref="ComposablePartExportProvider"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")]
- public ExportProvider SourceProvider
+ [DisallowNull]
+ public ExportProvider? SourceProvider
{
get
{
{
ThrowIfDisposed();
- Requires.NotNull(value, nameof(value));
+ Requires.NotNull(value!, nameof(value));
using (_lock.LockStateForWrite())
{
EnsureCanSet(_sourceProvider);
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- ImportEngine importEngine = new ImportEngine(_sourceProvider, _compositionOptions);
+ ImportEngine? importEngine = new ImportEngine(_sourceProvider, _compositionOptions);
using (_lock.LockStateForWrite())
{
if (_importEngine == null)
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export>? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
// failing that use the usual list. We never change the list of parts in place,
// but rather copy, change and write a new list atomically. Therefore all we need
// to do here is to read the _parts member.
- List<ComposablePart> parts = null;
+ List<ComposablePart>? parts = null;
using (_lock.LockStateForRead())
{
parts = atomicComposition.GetValueAllowNull(this, _parts);
// Copy the current list of parts - we are about to modify it
// This is an OK thing to do as this is the only method that can modify the List AND Compose can
// only be executed on one thread at a time - thus two different threads cannot tramp over each other
- List<ComposablePart> parts = null;
+ List<ComposablePart>? parts = null;
using (_lock.LockStateForRead())
{
parts = _parts.ToList(); // this copies the list
parts.Add(part);
}
- List<ComposablePart> partsToRemove = null;
+ List<ComposablePart>? partsToRemove = null;
foreach (ComposablePart part in batch.PartsToRemove)
{
return new Export(export, () => GetExportedValue(part, export));
}
- private object GetExportedValue(ComposablePart part, ExportDefinition export)
+ private object? GetExportedValue(ComposablePart part, ExportDefinition export)
{
ThrowIfDisposed();
EnsureRunning();
}
[DebuggerStepThrough]
- private void EnsureCanSet<T>(T currentValue)
+ private void EnsureCanSet<T>(T? currentValue)
where T : class
{
if ((_isRunning) || (currentValue != null))
_export = export;
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get { return MetadataServices.EmptyMetadata; }
}
get { return Enumerable.Empty<ImportDefinition>(); }
}
- public override object GetExportedValue(ExportDefinition definition)
+ public override object? GetExportedValue(ExportDefinition definition)
{
Requires.NotNull(definition, nameof(definition));
/// </summary>
/// <param name="partsToAdd">The parts to add.</param>
/// <param name="partsToRemove">The parts to remove.</param>
- public CompositionBatch(IEnumerable<ComposablePart> partsToAdd, IEnumerable<ComposablePart> partsToRemove)
+ public CompositionBatch(IEnumerable<ComposablePart>? partsToAdd, IEnumerable<ComposablePart>? partsToRemove)
{
_partsToAdd = new List<ComposablePart>();
if (partsToAdd != null)
{
private class CompositionServiceShim : ICompositionService
{
- private readonly CompositionContainer _innerContainer = null;
+ private readonly CompositionContainer _innerContainer;
public CompositionServiceShim(CompositionContainer innerContainer)
{
public partial class CompositionContainer : ExportProvider, ICompositionService, IDisposable
{
private readonly CompositionOptions _compositionOptions;
- private ImportEngine _importEngine;
+ private ImportEngine? _importEngine;
private ComposablePartExportProvider _partExportProvider;
private ExportProvider _rootProvider;
- private IDisposable _disposableRootProvider;
- private CatalogExportProvider _catalogExportProvider;
+ private IDisposable? _disposableRootProvider;
+ private CatalogExportProvider? _catalogExportProvider;
private ExportProvider _localExportProvider;
- private IDisposable _disposableLocalExportProvider;
- private ExportProvider _ancestorExportProvider;
- private IDisposable _disposableAncestorExportProvider;
+ private IDisposable? _disposableLocalExportProvider;
+ private ExportProvider? _ancestorExportProvider;
+ private IDisposable? _disposableAncestorExportProvider;
private readonly ReadOnlyCollection<ExportProvider> _providers;
private volatile bool _isDisposed = false;
/// Initializes a new instance of the <see cref="CompositionContainer"/> class.
/// </summary>
public CompositionContainer()
- : this((ComposablePartCatalog)null)
+ : this((ComposablePartCatalog?)null)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(params ExportProvider[] providers) :
- this((ComposablePartCatalog)null, providers)
+ public CompositionContainer(params ExportProvider[]? providers) :
+ this((ComposablePartCatalog?)null, providers)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(CompositionOptions compositionOptions, params ExportProvider[] providers) :
- this((ComposablePartCatalog)null, compositionOptions, providers)
+ public CompositionContainer(CompositionOptions compositionOptions, params ExportProvider[]? providers) :
+ this((ComposablePartCatalog?)null, compositionOptions, providers)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers) :
+ public CompositionContainer(ComposablePartCatalog? catalog, params ExportProvider[]? providers) :
this(catalog, false, providers)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(ComposablePartCatalog catalog, bool isThreadSafe, params ExportProvider[] providers)
+ public CompositionContainer(ComposablePartCatalog? catalog, bool isThreadSafe, params ExportProvider[]? providers)
: this(catalog, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default, providers)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
- public CompositionContainer(ComposablePartCatalog catalog, CompositionOptions compositionOptions, params ExportProvider[] providers)
+ public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions compositionOptions, params ExportProvider[]? providers)
{
if (compositionOptions > (CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService))
{
int customProviderStartIndex = 1;
if (catalog != null)
{
- rootProviders[1] = _catalogExportProvider;
+ rootProviders[1] = _catalogExportProvider!;
customProviderStartIndex = 2;
}
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
- public ComposablePartCatalog Catalog
+ public ComposablePartCatalog? Catalog
{
get
{
}
}
- internal CatalogExportProvider CatalogExportProvider
+ internal CatalogExportProvider? CatalogExportProvider
{
get
{
{
if (!_isDisposed)
{
- ExportProvider rootProvider = null;
- IDisposable disposableAncestorExportProvider = null;
- IDisposable disposableLocalExportProvider = null;
- IDisposable disposableRootProvider = null;
- ComposablePartExportProvider partExportProvider = null;
- CatalogExportProvider catalogExportProvider = null;
- ImportEngine importEngine = null;
+ ExportProvider? rootProvider = null;
+ IDisposable? disposableAncestorExportProvider = null;
+ IDisposable? disposableLocalExportProvider = null;
+ IDisposable? disposableRootProvider = null;
+ ComposablePartExportProvider? partExportProvider = null;
+ CatalogExportProvider? catalogExportProvider = null;
+ ImportEngine? importEngine = null;
lock (_lock)
{
if (!_isDisposed)
{
rootProvider = _rootProvider;
- _rootProvider = null;
+ _rootProvider = null!;
disposableRootProvider = _disposableRootProvider;
_disposableRootProvider = null;
disposableLocalExportProvider = _disposableLocalExportProvider;
_disposableLocalExportProvider = null;
- _localExportProvider = null;
+ _localExportProvider = null!;
disposableAncestorExportProvider = _disposableAncestorExportProvider;
_disposableAncestorExportProvider = null;
_ancestorExportProvider = null;
partExportProvider = _partExportProvider;
- _partExportProvider = null;
+ _partExportProvider = null!;
catalogExportProvider = _catalogExportProvider;
_catalogExportProvider = null;
{
Requires.NotNull(export, nameof(export));
- IDisposable dependency = export as IDisposable;
-
- if (dependency != null)
+ if (export is IDisposable dependency)
{
dependency.Dispose();
}
{
Requires.NotNull(export, nameof(export));
- IDisposable dependency = export as IDisposable;
-
- if (dependency != null)
+ if (export is IDisposable dependency)
{
dependency.Dispose();
}
if (_importEngine == null)
{
- ImportEngine importEngine = new ImportEngine(this, _compositionOptions);
+ ImportEngine? importEngine = new ImportEngine(this, _compositionOptions);
lock (_lock)
{
_importEngine.SatisfyImportsOnce(part);
}
- internal void OnExportsChangedInternal(object sender, ExportsChangeEventArgs e)
+ internal void OnExportsChangedInternal(object? sender, ExportsChangeEventArgs e)
{
OnExportsChanged(e);
}
- internal void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
+ internal void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e)
{
OnExportsChanging(e);
}
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+ protected override IEnumerable<Export>? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
- IEnumerable<Export> exports = null;
+ IEnumerable<Export>? exports = null;
- object source;
- if (!definition.Metadata.TryGetValue(CompositionConstants.ImportSourceMetadataName, out source))
+ if (!definition.Metadata.TryGetValue(CompositionConstants.ImportSourceMetadataName, out object? source))
{
source = ImportSource.Any;
}
- switch ((ImportSource)source)
+ switch ((ImportSource)source!)
{
case ImportSource.Any:
if (_rootProvider == null)
internal sealed class CompositionLock : IDisposable
{
// narrow lock
- private readonly Lock _stateLock = null;
+ private readonly Lock? _stateLock = null;
// wide lock
private static readonly object _compositionLock = new object();
{
if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
{
- _stateLock.Dispose();
+ _stateLock!.Dispose();
}
}
}
{
if (_isThreadSafe)
{
- return new ReadLock(_stateLock);
+ return new ReadLock(_stateLock!);
}
else
{
{
if (_isThreadSafe)
{
- return new WriteLock(_stateLock);
+ return new WriteLock(_stateLock!);
}
else
{
[DebuggerTypeProxy(typeof(CompositionScopeDefinitionDebuggerProxy))]
public class CompositionScopeDefinition : ComposablePartCatalog, INotifyComposablePartCatalogChanged
{
- private ComposablePartCatalog _catalog;
- private IEnumerable<ExportDefinition> _publicSurface = null;
+ private ComposablePartCatalog? _catalog;
+ private IEnumerable<ExportDefinition>? _publicSurface = null;
private IEnumerable<CompositionScopeDefinition> _children = Enumerable.Empty<CompositionScopeDefinition>();
private volatile int _isDisposed = 0;
/// </summary>
/// <param name="catalog">The catalog.</param>
/// <param name="children">The children.</param>
- private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable<CompositionScopeDefinition> children, IEnumerable<ExportDefinition> publicSurface)
+ private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable<CompositionScopeDefinition>? children, IEnumerable<ExportDefinition>? publicSurface)
{
_catalog = catalog;
if (children != null)
_publicSurface = publicSurface;
}
- INotifyComposablePartCatalogChanged notifyCatalog = _catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
+ if (_catalog is INotifyComposablePartCatalogChanged notifyCatalog)
{
notifyCatalog.Changed += OnChangedInternal;
notifyCatalog.Changing += OnChangingInternal;
{
if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
{
- INotifyComposablePartCatalogChanged notifyCatalog = _catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
+ if (_catalog is INotifyComposablePartCatalogChanged notifyCatalog)
{
notifyCatalog.Changed -= OnChangedInternal;
notifyCatalog.Changing -= OnChangingInternal;
/// <value>The children.</value>
public override IEnumerator<ComposablePartDefinition> GetEnumerator()
{
+ Debug.Assert(_catalog != null);
return _catalog.GetEnumerator();
}
{
ThrowIfDisposed();
+ Debug.Assert(_catalog != null);
return _catalog.GetExports(definition);
}
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
/// <summary>
/// Notify when the contents of the Catalog is changing.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
/// <summary>
/// Raises the <see cref="Changed"/> event.
/// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
if (changedEvent != null)
{
changedEvent.Invoke(this, e);
/// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changingEvent = Changing;
if (changingEvent != null)
{
changingEvent.Invoke(this, e);
}
}
- private void OnChangedInternal(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e)
{
OnChanged(e);
}
- private void OnChangingInternal(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEventArgs e)
{
OnChanging(e);
}
/// </remarks>
public class CompositionService : ICompositionService, IDisposable
{
- private readonly CompositionContainer _compositionContainer = null;
- private readonly INotifyComposablePartCatalogChanged _notifyCatalog = null;
+ private readonly CompositionContainer? _compositionContainer = null;
+ private readonly INotifyComposablePartCatalogChanged? _notifyCatalog = null;
internal CompositionService(ComposablePartCatalog composablePartCatalog)
{
_compositionContainer.Dispose();
}
- private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e)
{
throw new ChangeRejectedException(SR.NotSupportedCatalogChanges);
}
}
}
- internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type memberType)
+ internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type? memberType)
{
if (specifiedContractType == null)
{
return GenericServices.GetGenericName(originalTypeIdentity, GenericServices.GetGenericParametersOrder(typeIdentityType), GenericServices.GetPureGenericArity(typeIdentityType));
}
- internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type typeIdentityType, out string contractName)
+ internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type? typeIdentityType, out string contractName)
{
typeIdentityType = member.GetTypeIdentityTypeFromExport(export);
if (!string.IsNullOrEmpty(export.ContractName))
}
}
- internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType)
+ internal static string GetTypeIdentityFromExport(this MemberInfo member, Type? typeIdentityType)
{
if (typeIdentityType != null)
{
}
else
{
- MethodInfo method = member as MethodInfo;
+ MethodInfo? method = member as MethodInfo;
if (method == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
}
- private static Type GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export)
+ private static Type? GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export)
{
if (export.ContractType != null)
{
return AttributedModelServices.GetContractName(contractType);
}
- internal static string GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType)
+ internal static string? GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType)
{
Type contractType = import.GetContractTypeFromImport(importType);
return AttributedModelServices.GetTypeIdentity(contractType);
}
- internal static IDictionary<string, object> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy)
+ internal static IDictionary<string, object?> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy)
{
- IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparers.MetadataKeyNames);
+ IDictionary<string, object?> dictionary = new Dictionary<string, object?>(StringComparers.MetadataKeyNames);
if (creationPolicy != CreationPolicy.Any)
{
// add constraints
bool hasConstraints = false;
- object[] genericParameterConstraints = new object[genericArguments.Length];
+ object?[] genericParameterConstraints = new object?[genericArguments.Length];
GenericParameterAttributes[] genericParameterAttributes = new GenericParameterAttributes[genericArguments.Length];
for (int i = 0; i < genericArguments.Length; i++)
{
Type genericArgument = genericArguments[i];
- Type[] constraints = genericArgument.GetGenericParameterConstraints();
+ Type[]? constraints = genericArgument.GetGenericParameterConstraints();
if (constraints.Length == 0)
{
constraints = null;
}
}
- internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object> dictionary)
+ internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object?> dictionary)
{
- dictionary = new Dictionary<string, object>();
+ dictionary = new Dictionary<string, object?>();
foreach (var attr in member.GetAttributes<Attribute>())
{
if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined<MetadataAttributeAttribute>(true))
{
bool allowsMultiple = false;
- AttributeUsageAttribute usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true);
+ AttributeUsageAttribute? usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true);
if (usage != null)
{
if (reservedMetadataNames.Contains(pi.Name, StringComparers.MetadataKeyNames))
{
- throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name);
+ throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, pi.GetDisplayName(), pi.Name);
}
- object value = pi.GetValue(attr, null);
+ object? value = pi.GetValue(attr, null);
if (value != null && !IsValidAttributeType(value.GetType()))
{
return;
}
- private static bool TryContributeMetadataValue(this IDictionary<string, object> dictionary, string name, object value, Type valueType, bool allowsMultiple)
+ private static bool TryContributeMetadataValue(this IDictionary<string, object?> dictionary, string name, object? value, Type? valueType, bool allowsMultiple)
{
- object metadataValue;
- if (!dictionary.TryGetValue(name, out metadataValue))
+ if (!dictionary.TryGetValue(name, out object? metadataValue))
{
if (allowsMultiple)
{
private class MetadataList
{
- private Type _arrayType = null;
+ private Type? _arrayType = null;
private bool _containsNulls = false;
private static readonly Type ObjectType = typeof(object);
private static readonly Type TypeType = typeof(Type);
- private readonly Collection<object> _innerList = new Collection<object>();
+ private readonly Collection<object?> _innerList = new Collection<object?>();
- public void Add(object item, Type itemType)
+ public void Add(object? item, Type? itemType)
{
_containsNulls |= (item == null);
// return result;
//}
- internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type metadataViewType)
+ internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type? metadataViewType)
{
if ((metadataViewType == null) ||
ExportServices.IsDefaultMetadataViewType(metadataViewType) ||
return properties.Select(property => new KeyValuePair<string, Type>(property.Name, property.PropertyType));
}
- internal static IDictionary<string, object> GetImportMetadata(ImportType importType, IAttributedImport attributedImport)
+ internal static IDictionary<string, object?> GetImportMetadata(ImportType importType, IAttributedImport attributedImport)
{
return GetImportMetadata(importType.ContractType, attributedImport);
}
- internal static IDictionary<string, object> GetImportMetadata(Type type, IAttributedImport attributedImport)
+ internal static IDictionary<string, object?> GetImportMetadata(Type type, IAttributedImport? attributedImport)
{
- Dictionary<string, object> metadata = null;
+ Dictionary<string, object?>? metadata = null;
//Prior to V4.5 MEF did not support ImportMetadata
if (type.IsGenericType)
{
- metadata = new Dictionary<string, object>();
+ metadata = new Dictionary<string, object?>();
if (type.ContainsGenericParameters)
{
{
if (metadata == null)
{
- metadata = new Dictionary<string, object>();
+ metadata = new Dictionary<string, object?>();
}
metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source;
}
}
}
- internal static object GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
+ internal static object? GetExportedValueFromComposedPart(ImportEngine? engine, ComposablePart part, ExportDefinition definition)
{
if (engine != null)
{
}
}
- internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _delegate, object sender, TEventArgs e)
+ internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _delegate, object? sender, TEventArgs e)
where TEventArgs : EventArgs
{
CompositionResult result = CompositionResult.SucceededResult;
internal static CreationPolicy GetRequiredCreationPolicy(this ImportDefinition definition)
{
- ContractBasedImportDefinition contractDefinition = definition as ContractBasedImportDefinition;
-
- if (contractDefinition != null)
+ if (definition is ContractBasedImportDefinition contractDefinition)
{
return contractDefinition.RequiredCreationPolicy;
}
// Single-dimensional arrays of the above types.
if (arrayAllowed && type.IsArray &&
type.GetArrayRank() == 1 &&
- IsValidAttributeType(type.GetElementType(), false))
+ IsValidAttributeType(type.GetElementType()!, false))
{
return true;
}
}
}
- public ReflectionContext ReflectionContext
+ public ReflectionContext? ReflectionContext
{
get
{
public partial class DirectoryCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement
{
private readonly Lock _thisLock = new Lock();
- private readonly ICompositionElement _definitionOrigin = null;
- private ComposablePartCatalogCollection _catalogCollection;
- private Dictionary<string, AssemblyCatalog> _assemblyCatalogs;
+ private readonly ICompositionElement? _definitionOrigin = null;
+ private ComposablePartCatalogCollection _catalogCollection = null!; // Always initialized with Initialize()
+ private Dictionary<string, AssemblyCatalog> _assemblyCatalogs = null!;
private volatile bool _isDisposed = false;
- private string _path;
- private string _fullPath;
- private string _searchPattern;
- private ReadOnlyCollection<string> _loadedFiles;
+ private string _path = null!;
+ private string _fullPath = null!;
+ private string _searchPattern = null!;
+ private ReadOnlyCollection<string> _loadedFiles = null!;
- private readonly ReflectionContext _reflectionContext = null;
+ private readonly ReflectionContext? _reflectionContext = null;
/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
/// <summary>
/// Releases unmanaged and - optionally - managed resources
if (!_isDisposed)
{
bool disposeLock = false;
- ComposablePartCatalogCollection catalogs = null;
+ ComposablePartCatalogCollection? catalogs = null;
try
{
{
disposeLock = true;
catalogs = _catalogCollection;
- _catalogCollection = null;
- _assemblyCatalogs = null;
+ _catalogCollection = null!;
+ _assemblyCatalogs = null!;
_isDisposed = true;
}
}
/// </param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
if (changedEvent != null)
{
changedEvent(this, e);
/// </param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changingEvent = Changing;
if (changingEvent != null)
{
changingEvent(this, e);
return GetDisplayName();
}
- private AssemblyCatalog CreateAssemblyCatalogGuarded(string assemblyFilePath)
+ private AssemblyCatalog? CreateAssemblyCatalogGuarded(string assemblyFilePath)
{
- Exception exception = null;
+ Exception? exception = null;
try
{
IEnumerable<string> filesToAdd = afterFiles.Except(beforeFiles);
foreach (string file in filesToAdd)
{
- AssemblyCatalog catalog = CreateAssemblyCatalogGuarded(file);
+ AssemblyCatalog? catalog = CreateAssemblyCatalogGuarded(file);
if (catalog != null)
{
{
foreach (string file in filesToRemove)
{
- AssemblyCatalog catalog;
- if (_assemblyCatalogs.TryGetValue(file, out catalog))
+ if (_assemblyCatalogs.TryGetValue(file, out AssemblyCatalog? catalog))
{
catalogsToRemove.Add(new Tuple<string, AssemblyCatalog>(file, catalog));
}
foreach (string file in _loadedFiles)
{
- AssemblyCatalog assemblyCatalog = null;
- assemblyCatalog = CreateAssemblyCatalogGuarded(file);
+ AssemblyCatalog? assemblyCatalog = CreateAssemblyCatalogGuarded(file);
if (assemblyCatalog != null)
{
/// This property always returns <see langword="null"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return null; }
}
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
- public Lazy<T> GetExport<T>()
+ public Lazy<T>? GetExport<T>()
{
- return GetExport<T>((string)null);
+ return GetExport<T>((string?)null);
}
/// <summary>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
- public Lazy<T> GetExport<T>(string contractName)
+ public Lazy<T>? GetExport<T>(string? contractName)
{
return GetExportCore<T>(contractName);
}
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
- public Lazy<T, TMetadataView> GetExport<T, TMetadataView>()
+ public Lazy<T, TMetadataView>? GetExport<T, TMetadataView>()
{
- return GetExport<T, TMetadataView>((string)null);
+ return GetExport<T, TMetadataView>((string?)null);
}
/// <summary>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
- public Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName)
+ public Lazy<T, TMetadataView>? GetExport<T, TMetadataView>(string? contractName)
{
return GetExportCore<T, TMetadataView>(contractName);
}
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<object, object>> GetExports(Type type, Type metadataViewType, string contractName)
+ public IEnumerable<Lazy<object, object>> GetExports(Type type, Type? metadataViewType, string? contractName)
{
IEnumerable<Export> exports = GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore);
Collection<Lazy<object, object>> result = new Collection<Lazy<object, object>>();
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T>> GetExports<T>()
{
- return GetExports<T>((string)null);
+ return GetExports<T>((string?)null);
}
/// <summary>
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T>> GetExports<T>(string contractName)
+ public IEnumerable<Lazy<T>> GetExports<T>(string? contractName)
{
return GetExportsCore<T>(contractName);
}
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>()
{
- return GetExports<T, TMetadataView>((string)null);
+ return GetExports<T, TMetadataView>((string?)null);
}
/// <summary>
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName)
+ public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string? contractName)
{
return GetExportsCore<T, TMetadataView>(contractName);
}
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
+ [return: MaybeNull]
public T GetExportedValue<T>()
{
- return GetExportedValue<T>((string)null);
+ return GetExportedValue<T>((string?)null);
}
/// <summary>
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
- public T GetExportedValue<T>(string contractName)
+ [return: MaybeNull]
+ public T GetExportedValue<T>(string? contractName)
{
return GetExportedValueCore<T>(contractName, ImportCardinality.ExactlyOne);
}
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
+ [return: MaybeNull]
public T GetExportedValueOrDefault<T>()
{
- return GetExportedValueOrDefault<T>((string)null);
+ return GetExportedValueOrDefault<T>((string?)null);
}
/// <summary>
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
- public T GetExportedValueOrDefault<T>(string contractName)
+ [return: MaybeNull]
+ public T GetExportedValueOrDefault<T>(string? contractName)
{
return GetExportedValueCore<T>(contractName, ImportCardinality.ZeroOrOne);
}
/// </exception>
public IEnumerable<T> GetExportedValues<T>()
{
- return GetExportedValues<T>((string)null);
+ return GetExportedValues<T>((string?)null);
}
/// <summary>
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
- public IEnumerable<T> GetExportedValues<T>(string contractName)
+ public IEnumerable<T> GetExportedValues<T>(string? contractName)
{
return GetExportedValuesCore<T>(contractName);
}
- private IEnumerable<T> GetExportedValuesCore<T>(string contractName)
+ private IEnumerable<T> GetExportedValuesCore<T>(string? contractName)
{
- IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
+ IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore);
Collection<T> result = new Collection<T>();
foreach (Export export in exports)
return result;
}
- private T GetExportedValueCore<T>(string contractName, ImportCardinality cardinality)
+ [return: MaybeNull]
+ private T GetExportedValueCore<T>(string? contractName, ImportCardinality cardinality)
{
if (!cardinality.IsAtMostOne())
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- Export export = GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault();
+ Export? export = GetExportsCore(typeof(T), (Type?)null, contractName, cardinality).SingleOrDefault();
- return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T);
+ return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T)!;
}
- private IEnumerable<Lazy<T>> GetExportsCore<T>(string contractName)
+ private IEnumerable<Lazy<T>> GetExportsCore<T>(string? contractName)
{
- IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
+ IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore);
Collection<Lazy<T>> result = new Collection<Lazy<T>>();
foreach (Export export in exports)
return result;
}
- private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string contractName)
+ private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string? contractName)
{
IEnumerable<Export> exports = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore);
return result;
}
- private Lazy<T, TMetadataView> GetExportCore<T, TMetadataView>(string contractName)
+ private Lazy<T, TMetadataView>? GetExportCore<T, TMetadataView>(string? contractName)
{
- Export export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
+ Export? export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export) : null;
}
- private Lazy<T> GetExportCore<T>(string contractName)
+ private Lazy<T>? GetExportCore<T>(string? contractName)
{
- Export export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
+ Export? export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT<T>(export) : null;
}
- private IEnumerable<Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
+ private IEnumerable<Export> GetExportsCore(Type type, Type? metadataViewType, string? contractName, ImportCardinality cardinality)
{
// Only 'type' cannot be null - the other parameters have sensible defaults.
Requires.NotNull(type, nameof(type));
}
IEnumerable<KeyValuePair<string, Type>> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType);
- IDictionary<string, object> metadata = CompositionServices.GetImportMetadata(type, null);
+ IDictionary<string, object?> metadata = CompositionServices.GetImportMetadata(type, null);
- string requiredTypeIdentity = null;
+ string? requiredTypeIdentity = null;
if (type != typeof(object))
{
requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type);
/// <summary>
/// Occurs when the exports in the <see cref="ExportProvider"/> have changed.
/// </summary>
- public event EventHandler<ExportsChangeEventArgs> ExportsChanged;
+ public event EventHandler<ExportsChangeEventArgs>? ExportsChanged;
/// <summary>
/// Occurs when the exports in the <see cref="ExportProvider"/> are changing.
/// </summary>
- public event EventHandler<ExportsChangeEventArgs> ExportsChanging;
+ public event EventHandler<ExportsChangeEventArgs>? ExportsChanging;
/// <summary>
/// Returns all exports that match the conditions of the specified import.
/// objects that match the conditions of the specified <see cref="ImportDefinition"/>.
/// </para>
/// </exception>
- public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
+ public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition? atomicComposition)
{
Requires.NotNull(definition, nameof(definition));
- IEnumerable<Export> exports;
- ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
+ ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out IEnumerable<Export>? exports);
switch (result)
{
case ExportCardinalityCheckResult.Match:
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
- public bool TryGetExports(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
+ public bool TryGetExports(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable<Export>? exports)
{
Requires.NotNull(definition, nameof(definition));
- exports = null;
ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
return (result == ExportCardinalityCheckResult.Match);
}
/// specified <see cref="ImportDefinition"/>, an <see cref="IEnumerable{T}"/> should be returned.
/// </note>
/// </remarks>
- protected abstract IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition);
+ protected abstract IEnumerable<Export>? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition);
/// <summary>
/// Raises the <see cref="ExportsChanged"/> event.
/// </param>
protected virtual void OnExportsChanged(ExportsChangeEventArgs e)
{
- EventHandler<ExportsChangeEventArgs> changedEvent = ExportsChanged;
+ EventHandler<ExportsChangeEventArgs>? changedEvent = ExportsChanged;
if (changedEvent != null)
{
CompositionResult result = CompositionServices.TryFire(changedEvent, this, e);
/// </param>
protected virtual void OnExportsChanging(ExportsChangeEventArgs e)
{
- EventHandler<ExportsChangeEventArgs> changingEvent = ExportsChanging;
+ EventHandler<ExportsChangeEventArgs>? changingEvent = ExportsChanging;
if (changingEvent != null)
{
CompositionResult result = CompositionServices.TryFire(changingEvent, this, e);
}
}
- private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
+ private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable<Export>? exports)
{
if (definition == null)
{
{
private readonly IEnumerable<ExportDefinition> _addedExports;
private readonly IEnumerable<ExportDefinition> _removedExports;
- private IEnumerable<string> _changedContractNames = null;
+ private IEnumerable<string>? _changedContractNames = null;
/// <summary>
/// Initializes a new instance of the <see cref="ExportsChangeEventArgs"/> class with
/// <paramref name="addedExports"/> or <paramref name="removedExports"/> is <see langword="null"/>.
/// </exception>
public ExportsChangeEventArgs(IEnumerable<ExportDefinition> addedExports,
- IEnumerable<ExportDefinition> removedExports, AtomicComposition atomicComposition)
+ IEnumerable<ExportDefinition> removedExports, AtomicComposition? atomicComposition)
{
Requires.NotNull(addedExports, nameof(addedExports));
Requires.NotNull(removedExports, nameof(removedExports));
/// When the value is non-null it should be used to record temporary changed state
/// and actions that will be executed when the atomicComposition is completeed.
/// </value>
- public AtomicComposition AtomicComposition { get; private set; }
+ public AtomicComposition? AtomicComposition { get; private set; }
}
}
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics;
namespace System.ComponentModel.Composition.Hosting
{
{
private readonly IEnumerable<ComposablePartDefinition> _parts;
private readonly Func<ImportDefinition, bool> _importFilter;
- private Dictionary<string, List<ComposablePartDefinition>> _exportersIndex;
+ private Dictionary<string, List<ComposablePartDefinition>>? _exportersIndex;
public DependenciesTraversal(FilteredCatalog catalog, Func<ImportDefinition, bool> importFilter)
{
private void AddToExportersIndex(string contractName, ComposablePartDefinition part)
{
- List<ComposablePartDefinition> parts = null;
- if (!_exportersIndex.TryGetValue(contractName, out parts))
+ if (!_exportersIndex!.TryGetValue(contractName, out List<ComposablePartDefinition>? parts))
{
parts = new List<ComposablePartDefinition>();
_exportersIndex.Add(contractName, parts);
parts.Add(part);
}
- public bool TryTraverse(ComposablePartDefinition part, out IEnumerable<ComposablePartDefinition> reachableParts)
+ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts)
{
reachableParts = null;
- List<ComposablePartDefinition> reachablePartList = null;
+ List<ComposablePartDefinition>? reachablePartList = null;
// Go through all part imports
foreach (ImportDefinition import in part.ImportDefinitions.Where(_importFilter))
{
// Find all parts that we know will import each export
- List<ComposablePartDefinition> candidateReachableParts = null;
+ List<ComposablePartDefinition>? candidateReachableParts = null;
+ Debug.Assert(_exportersIndex != null);
foreach (var contractName in import.GetCandidateContractNames(part))
{
if (_exportersIndex.TryGetValue(contractName, out candidateReachableParts))
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.Hosting
{
{
private readonly IEnumerable<ComposablePartDefinition> _parts;
private readonly Func<ImportDefinition, bool> _importFilter;
- private Dictionary<string, List<ComposablePartDefinition>> _importersIndex;
+ private Dictionary<string, List<ComposablePartDefinition>>? _importersIndex;
public DependentsTraversal(FilteredCatalog catalog, Func<ImportDefinition, bool> importFilter)
{
private void AddToImportersIndex(string contractName, ComposablePartDefinition part)
{
- List<ComposablePartDefinition> parts = null;
- if (!_importersIndex.TryGetValue(contractName, out parts))
+ if (!_importersIndex!.TryGetValue(contractName, out List<ComposablePartDefinition>? parts))
{
parts = new List<ComposablePartDefinition>();
_importersIndex.Add(contractName, parts);
parts.Add(part);
}
- public bool TryTraverse(ComposablePartDefinition part, out IEnumerable<ComposablePartDefinition> reachableParts)
+ public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts)
{
reachableParts = null;
- List<ComposablePartDefinition> reachablePartList = null;
+ List<ComposablePartDefinition>? reachablePartList = null;
+ Debug.Assert(_importersIndex != null);
// Go through all part exports
foreach (ExportDefinition export in part.ExportDefinitions)
{
// Find all parts that we know will import each export
- List<ComposablePartDefinition> candidateReachableParts = null;
+ List<ComposablePartDefinition>? candidateReachableParts = null;
if (_importersIndex.TryGetValue(export.ContractName, out candidateReachableParts))
{
// find if they actually match
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.Hosting
{
internal interface IComposablePartCatalogTraversal
{
void Initialize();
- bool TryTraverse(ComposablePartDefinition part, out IEnumerable<ComposablePartDefinition> reachableParts);
+ bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts);
}
}
}
{
if (traversedParts.Add(part))
{
- IEnumerable<ComposablePartDefinition> partsToTraverse = null;
- if (traversal.TryTraverse(part, out partsToTraverse))
+ if (traversal.TryTraverse(part, out IEnumerable<ComposablePartDefinition>? partsToTraverse))
{
GetTraversalClosure(partsToTraverse, traversedParts, traversal);
}
private void FreezeInnerCatalog()
{
- INotifyComposablePartCatalogChanged innerNotifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged;
- if (innerNotifyCatalog != null)
+ if (_innerCatalog is INotifyComposablePartCatalogChanged innerNotifyCatalog)
{
innerNotifyCatalog.Changing += ThrowOnRecomposition;
}
private void UnfreezeInnerCatalog()
{
- INotifyComposablePartCatalogChanged innerNotifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged;
- if (innerNotifyCatalog != null)
+ if (_innerCatalog is INotifyComposablePartCatalogChanged innerNotifyCatalog)
{
innerNotifyCatalog.Changing -= ThrowOnRecomposition;
}
}
- private static void ThrowOnRecomposition(object sender, ComposablePartCatalogChangeEventArgs e)
+ private static void ThrowOnRecomposition(object? sender, ComposablePartCatalogChangeEventArgs e)
{
throw new ChangeRejectedException();
}
{
private readonly Func<ComposablePartDefinition, bool> _filter;
private ComposablePartCatalog _innerCatalog;
- private FilteredCatalog _complement;
+ private FilteredCatalog? _complement;
private readonly object _lock = new object();
private volatile bool _isDisposed = false;
{
}
- internal FilteredCatalog(ComposablePartCatalog catalog, Func<ComposablePartDefinition, bool> filter, FilteredCatalog complement)
+ internal FilteredCatalog(ComposablePartCatalog catalog, Func<ComposablePartDefinition, bool> filter, FilteredCatalog? complement)
{
Requires.NotNull(catalog, nameof(catalog));
Requires.NotNull(filter, nameof(filter));
_filter = (p) => filter.Invoke(p.GetGenericPartDefinition() ?? p);
_complement = complement;
- INotifyComposablePartCatalogChanged notifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
+ if (_innerCatalog is INotifyComposablePartCatalogChanged notifyCatalog)
{
notifyCatalog.Changed += OnChangedInternal;
notifyCatalog.Changing += OnChangingInternal;
{
if (!_isDisposed)
{
- INotifyComposablePartCatalogChanged notifyCatalog = null;
+ INotifyComposablePartCatalogChanged? notifyCatalog = null;
try
{
lock (_lock)
{
_isDisposed = true;
notifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged;
- _innerCatalog = null;
+ _innerCatalog = null!;
}
}
}
if (_complement == null)
{
- FilteredCatalog complement = new FilteredCatalog(_innerCatalog, p => !_filter(p), this);
+ FilteredCatalog? complement = new FilteredCatalog(_innerCatalog, p => !_filter(p), this);
lock (_lock)
{
if (_complement == null)
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
/// <summary>
/// Notify when the contents of the Catalog is changing.
/// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
/// <summary>
/// Raises the <see cref="Changed"/> event.
/// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
if (changedEvent != null)
{
changedEvent.Invoke(this, e);
/// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
- EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+ EventHandler<ComposablePartCatalogChangeEventArgs>? changingEvent = Changing;
if (changingEvent != null)
{
changingEvent.Invoke(this, e);
}
}
- private void OnChangedInternal(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e)
{
var processedArgs = ProcessEventArgs(e);
if (processedArgs != null)
{
- OnChanged(ProcessEventArgs(processedArgs));
+ OnChanged(ProcessEventArgs(processedArgs)!);
}
}
- private void OnChangingInternal(object sender, ComposablePartCatalogChangeEventArgs e)
+ private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEventArgs e)
{
var processedArgs = ProcessEventArgs(e);
if (processedArgs != null)
{
- OnChanging(ProcessEventArgs(processedArgs));
+ OnChanging(ProcessEventArgs(processedArgs)!);
}
}
- private ComposablePartCatalogChangeEventArgs ProcessEventArgs(ComposablePartCatalogChangeEventArgs e)
+ private ComposablePartCatalogChangeEventArgs? ProcessEventArgs(ComposablePartCatalogChangeEventArgs e)
{
// the constructor for ComposablePartCatalogChangeEventArgs takes a snapshot of the arguments, so we don't have to
var result = new ComposablePartCatalogChangeEventArgs(
/// </summary>
public interface INotifyComposablePartCatalogChanged
{
- event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
- event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+ event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
+ event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
}
}
private readonly ImportEngine _importEngine;
private readonly List<PartManager> _addedPartManagers = new List<PartManager>();
private readonly List<PartManager> _removedPartManagers = new List<PartManager>();
- private readonly EngineContext _parentEngineContext;
+ private readonly EngineContext? _parentEngineContext;
- public EngineContext(ImportEngine importEngine, EngineContext parentEngineContext)
+ public EngineContext(ImportEngine importEngine, EngineContext? parentEngineContext)
{
_importEngine = importEngine;
_parentEngineContext = parentEngineContext;
}
}
- public IEnumerable<PartManager> GetAddedPartManagers()
+ public IEnumerable<PartManager>? GetAddedPartManagers()
{
if (_parentEngineContext != null)
{
return _addedPartManagers;
}
- public IEnumerable<PartManager> GetRemovedPartManagers()
+ public IEnumerable<PartManager>? GetRemovedPartManagers()
{
if (_parentEngineContext != null)
{
/// </summary>
private class PartManager
{
- private Dictionary<ImportDefinition, List<IDisposable>> _importedDisposableExports;
- private Dictionary<ImportDefinition, Export[]> _importCache;
- private string[] _importedContractNames;
+ private Dictionary<ImportDefinition, List<IDisposable>>? _importedDisposableExports;
+ private Dictionary<ImportDefinition, Export[]?>? _importCache;
+ private string[]? _importedContractNames;
private readonly ComposablePart _part;
private ImportState _state = ImportState.NoImportsSatisfied;
private readonly ImportEngine _importEngine;
}
}
- public void SetSavedImport(ImportDefinition import, Export[] exports, AtomicComposition atomicComposition)
+ public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicComposition? atomicComposition)
{
if (atomicComposition != null)
{
if (_importCache == null)
{
- _importCache = new Dictionary<ImportDefinition, Export[]>();
+ _importCache = new Dictionary<ImportDefinition, Export[]?>();
}
_importCache[import] = exports;
}
- public Export[] GetSavedImport(ImportDefinition import)
+ public Export[]? GetSavedImport(ImportDefinition import)
{
- Export[] exports = null;
+ Export[]? exports = null;
if (_importCache != null)
{
// We don't care about the return value we just want the exports
{
// Determine if there are any new disposable exports, optimizing for the most
// likely case, which is that there aren't any
- List<IDisposable> disposableExports = null;
+ List<IDisposable>? disposableExports = null;
foreach (var export in exports)
{
- IDisposable disposableExport = export as IDisposable;
- if (disposableExport != null)
+ if (export is IDisposable disposableExport)
{
if (disposableExports == null)
{
}
// Dispose any existing references previously set on this import
- List<IDisposable> oldDisposableExports = null;
+ List<IDisposable>? oldDisposableExports = null;
if (_importedDisposableExports != null &&
_importedDisposableExports.TryGetValue(import, out oldDisposableExports))
{
public IEnumerable<PartManager> GetPartsImporting(string contractName)
{
- WeakReferenceCollection<PartManager> partManagerList;
- if (!_partManagerIndex.TryGetValue(contractName, out partManagerList))
+ if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? partManagerList))
{
return Enumerable.Empty<PartManager>();
}
{
foreach (string contractName in partManager.GetImportedContractNames())
{
- WeakReferenceCollection<PartManager> indexEntries;
- if (!_partManagerIndex.TryGetValue(contractName, out indexEntries))
+ if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? indexEntries))
{
indexEntries = new WeakReferenceCollection<PartManager>();
_partManagerIndex.Add(contractName, indexEntries);
{
foreach (string contractName in partManager.GetImportedContractNames())
{
- WeakReferenceCollection<PartManager> indexEntries;
- if (_partManagerIndex.TryGetValue(contractName, out indexEntries))
+ if (_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? indexEntries))
{
indexEntries.Remove(partManager);
var aliveItems = indexEntries.AliveItemsToList();
var partsToIndex = _partsToIndex.AliveItemsToList();
_partsToIndex.Clear();
- var partsToUnindex = _partsToUnindex.AliveItemsToList();
+ List<PartManager?> partsToUnindex = _partsToUnindex.AliveItemsToList()!;
_partsToUnindex.Clear();
if (partsToIndex.Count == 0 && partsToUnindex.Count == 0)
private const int MaximumNumberOfCompositionIterations = 100;
private volatile bool _isDisposed;
- private ExportProvider _sourceProvider;
+ private ExportProvider? _sourceProvider;
private readonly Stack<PartManager> _recursionStateStack = new Stack<PartManager>();
private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>();
private RecompositionManager _recompositionManager = new RecompositionManager();
- private readonly CompositionLock _lock = null;
+ private readonly CompositionLock _lock;
private readonly CompositionOptions _compositionOptions;
/// <summary>
/// <exception cref="ObjectDisposedException">
/// The <see cref="ImportEngine"/> has been disposed of.
/// </exception>
- public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition)
+ public void PreviewImports(ComposablePart part, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
// We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless.
// This will take the lock, if necesary
- IDisposable compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null;
+ IDisposable? compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null;
bool compositionLockTaken = (compositionLockHolder != null);
try
{
// revert actions are processed in the reverse order, so we have to add the "release lock" action now
if (compositionLockTaken && (atomicComposition != null))
{
- atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose());
+ atomicComposition.AddRevertAction(() => compositionLockHolder!.Dispose());
}
- var partManager = GetPartManager(part, true);
+ var partManager = GetPartManager(part, true)!;
var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition);
result.ThrowOnErrors(atomicComposition);
// Add the "release lock" to the commit actions
if (compositionLockTaken && (atomicComposition != null))
{
- atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose());
+ atomicComposition.AddCompleteAction(() => compositionLockHolder!.Dispose());
}
}
finally
// We haven't updated the queues, so we can release the lock now
if (compositionLockTaken && (atomicComposition == null))
{
- compositionLockHolder.Dispose();
+ compositionLockHolder!.Dispose();
}
}
}
Requires.NotNull(part, nameof(part));
// NOTE : the following two calls use the state lock
- PartManager partManager = GetPartManager(part, true);
+ PartManager partManager = GetPartManager(part, true)!;
if (partManager.State == ImportState.Composed)
{
return;
Requires.NotNull(part, nameof(part));
// NOTE : the following two calls use the state lock
- PartManager partManager = GetPartManager(part, true);
+ PartManager partManager = GetPartManager(part, true)!;
if (partManager.State == ImportState.Composed)
{
return;
/// <param name="atomicComposition">
/// The <see cref="AtomicComposition"/> that the release imports is running under.
/// </param>
- public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition)
+ public void ReleaseImports(ComposablePart part, AtomicComposition? atomicComposition)
{
ThrowIfDisposed();
using (_lock.LockComposition())
{
- PartManager partManager = GetPartManager(part, false);
+ PartManager? partManager = GetPartManager(part, false);
if (partManager != null)
{
StopSatisfyingImports(partManager, atomicComposition);
if (!_isDisposed)
{
bool disposeLock = false;
- ExportProvider sourceProviderToUnsubscribeFrom = null;
+ ExportProvider? sourceProviderToUnsubscribeFrom = null;
using (_lock.LockStateForWrite())
{
if (!_isDisposed)
{
sourceProviderToUnsubscribeFrom = _sourceProvider;
_sourceProvider = null;
- _recompositionManager = null;
- _partManagers = null;
+ _recompositionManager = null!;
+ _partManagers = null!;
_isDisposed = true;
disposeLock = true;
}
}
private CompositionResult TryPreviewImportsStateMachine(PartManager partManager,
- ComposablePart part, AtomicComposition atomicComposition)
+ ComposablePart part, AtomicComposition? atomicComposition)
{
var result = CompositionResult.SucceededResult;
}
private CompositionResult TrySatisfyImportSubset(PartManager partManager,
- IEnumerable<ImportDefinition> imports, AtomicComposition atomicComposition)
+ IEnumerable<ImportDefinition> imports, AtomicComposition? atomicComposition)
{
CompositionResult result = CompositionResult.SucceededResult;
return result;
}
- private void OnExportsChanging(object sender, ExportsChangeEventArgs e)
+ private void OnExportsChanging(object? sender, ExportsChangeEventArgs e)
{
CompositionResult result = CompositionResult.SucceededResult;
// Prepare for the recomposition effort by minimizing the amount of work we'll have to do later
- AtomicComposition atomicComposition = e.AtomicComposition;
+ AtomicComposition? atomicComposition = e.AtomicComposition;
IEnumerable<PartManager> affectedParts = _recompositionManager.GetAffectedParts(e.ChangedContractNames);
// index
if (atomicComposition != null)
{
- EngineContext engineContext;
- if (atomicComposition.TryGetValue(this, out engineContext))
+ if (atomicComposition.TryGetValue(this, out EngineContext? engineContext))
{
// always added the new part managers to see if they will also be
// affected by these changes
- affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers())
- .Except(engineContext.GetRemovedPartManagers());
+ affectedParts = affectedParts.ConcatAllowingNull(engineContext!.GetAddedPartManagers())!
+ .Except(engineContext.GetRemovedPartManagers()!);
}
}
foreach (var partManager in affectedParts)
{
- result = result.MergeResult(TryRecomposeImports(partManager, changedExports, atomicComposition));
+ result = result.MergeResult(TryRecomposeImports(partManager, changedExports!, atomicComposition));
}
result.ThrowOnErrors(atomicComposition);
}
private CompositionResult TryRecomposeImports(PartManager partManager,
- IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
+ IEnumerable<ExportDefinition> changedExports, AtomicComposition? atomicComposition)
{
var result = CompositionResult.SucceededResult;
}
private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed,
- ImportDefinition import, AtomicComposition atomicComposition)
+ ImportDefinition import, AtomicComposition? atomicComposition)
{
if (partComposed && !import.IsRecomposable)
{
return CompositionResult.SucceededResult;
}
- private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
+ private void StartSatisfyingImports(PartManager partManager, AtomicComposition? atomicComposition)
{
// When not running in a atomicCompositional state, schedule reindexing after ensuring
// that this isn't a redundant addition
}
}
- private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
+ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? atomicComposition)
{
// When not running in a atomicCompositional state, schedule reindexing after ensuring
// that this isn't a redundant removal
if (atomicComposition == null)
{
- ConditionalWeakTable<ComposablePart, PartManager> partManagers = null;
- RecompositionManager recompositionManager = null;
+ ConditionalWeakTable<ComposablePart, PartManager>? partManagers = null;
+ RecompositionManager? recompositionManager = null;
using (_lock.LockStateForRead())
{
}
}
- private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent)
+ private PartManager? GetPartManager(ComposablePart part, bool createIfNotpresent)
{
- PartManager partManager = null;
+ PartManager? partManager = null;
using (_lock.LockStateForRead())
{
if (_partManagers.TryGetValue(part, out partManager))
throw new ArgumentNullException(nameof(atomicComposition));
}
- EngineContext engineContext;
- if (!atomicComposition.TryGetValue(this, true, out engineContext))
+ if (!atomicComposition.TryGetValue(this, true, out EngineContext? engineContext))
{
- EngineContext parentContext;
- atomicComposition.TryGetValue(this, false, out parentContext);
+ atomicComposition.TryGetValue(this, false, out EngineContext? parentContext);
engineContext = new EngineContext(this, parentContext);
atomicComposition.SetValue(this, engineContext);
atomicComposition.AddCompleteAction(engineContext.Complete);
}
- return engineContext;
+ return engineContext!;
}
private bool InPrerequisiteLoop()
{
PartManager firstPart = _recursionStateStack.First();
- PartManager lastPart = null;
+ PartManager? lastPart = null;
foreach (PartManager testPart in _recursionStateStack.Skip(1))
{
}
}
- private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider provider,
- ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition)
+ private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider? provider,
+ ComposablePart part, ImportDefinition definition, AtomicComposition? atomicComposition)
{
try
{
- IEnumerable<Export> exports = null;
+ IEnumerable<Export>? exports = null;
if (provider != null)
{
exports = provider.GetExports(definition, atomicComposition).AsArray();
}
- return new CompositionResult<IEnumerable<Export>>(exports);
+ return new CompositionResult<IEnumerable<Export>>(exports!);
}
catch (ImportCardinalityMismatchException ex)
{
internal class NonImportSourceImportDefinition : ContractBasedImportDefinition
{
private readonly ContractBasedImportDefinition _sourceDefinition;
- private IDictionary<string, object> _metadata;
+ private IDictionary<string, object?>? _metadata;
public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition)
{
get { return _sourceDefinition.ContractName; }
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
var reply = _metadata;
if (reply == null)
{
- reply = new Dictionary<string, object>(_sourceDefinition.Metadata);
+ reply = new Dictionary<string, object?>(_sourceDefinition.Metadata);
reply.Remove(CompositionConstants.ImportSourceMetadataName);
_metadata = reply;
}
return _sourceDefinition.ToString();
}
- public override string RequiredTypeIdentity
+ public override string? RequiredTypeIdentity
{
get { return _sourceDefinition.RequiredTypeIdentity; }
}
Requires.NotNull(part, nameof(part));
Requires.NotNull(key, nameof(key));
- object untypedValue = null;
- if (part.Metadata.TryGetValue(key, out untypedValue))
+ if (part.Metadata.TryGetValue(key, out object? untypedValue))
{
if (value == null)
{
public class TypeCatalog : ComposablePartCatalog, ICompositionElement
{
private readonly object _thisLock = new object();
- private Type[] _types = null;
- private volatile List<ComposablePartDefinition> _parts;
+ private Type[]? _types = null;
+ private volatile List<ComposablePartDefinition>? _parts;
private volatile bool _isDisposed = false;
private readonly ICompositionElement _definitionOrigin;
private readonly Lazy<IDictionary<string, List<ComposablePartDefinition>>> _contractPartIndex;
/// This property always returns <see langword="null"/>.
/// </value>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return null; }
}
}
}
- internal override IEnumerable<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition)
+ internal override IEnumerable<ComposablePartDefinition>? GetCandidateParts(ImportDefinition definition)
{
if (definition == null)
{
return PartsInternal;
}
- string genericContractName = definition.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
+ string? genericContractName = definition.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
- List<ComposablePartDefinition> nonGenericMatches = GetCandidateParts(contractName);
- List<ComposablePartDefinition> genericMatches = GetCandidateParts(genericContractName);
+ List<ComposablePartDefinition>? nonGenericMatches = GetCandidateParts(contractName);
+ List<ComposablePartDefinition>? genericMatches = GetCandidateParts(genericContractName);
return nonGenericMatches.ConcatAllowingNull(genericMatches);
}
- private List<ComposablePartDefinition> GetCandidateParts(string contractName)
+ private List<ComposablePartDefinition>? GetCandidateParts(string? contractName)
{
if (contractName == null)
{
return null;
}
- List<ComposablePartDefinition> contractCandidateParts = null;
- _contractPartIndex.Value.TryGetValue(contractName, out contractCandidateParts);
+ _contractPartIndex.Value.TryGetValue(contractName, out List<ComposablePartDefinition>? contractCandidateParts);
return contractCandidateParts;
}
{
foreach (string contractName in part.ExportDefinitions.Select(export => export.ContractName).Distinct())
{
- List<ComposablePartDefinition> contractParts = null;
+ List<ComposablePartDefinition>? contractParts = null;
if (!index.TryGetValue(contractName, out contractParts))
{
contractParts = new List<ComposablePartDefinition>();
{
internal interface IAttributedImport
{
- string ContractName { get; }
- Type ContractType { get; }
+ string? ContractName { get; }
+ Type? ContractType { get; }
bool AllowRecomposition { get; }
CreationPolicy RequiredCreationPolicy { get; }
ImportCardinality Cardinality { get; }
/// </para>
/// </remarks>
public ImportAttribute()
- : this((string)null)
+ : this((string?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ImportAttribute(Type contractType)
- : this((string)null, contractType)
+ public ImportAttribute(Type? contractType)
+ : this((string?)null, contractType)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ImportAttribute(string contractName)
- : this(contractName, (Type)null)
+ public ImportAttribute(string? contractName)
+ : this(contractName, (Type?)null)
{
}
- public ImportAttribute(string contractName, Type contractType)
+ public ImportAttribute(string? contractName, Type? contractType)
{
ContractName = contractName;
ContractType = contractType;
/// A <see cref="string"/> containing the contract name of the export to import. The
/// default value is an empty string ("").
/// </value>
- public string ContractName { get; private set; }
+ public string? ContractName { get; private set; }
/// <summary>
/// Get the contract type of the export to import.
/// the member that this import is attached to. If the type is <see cref="object"/> then the
/// importer is delaring they can accept any exported type.
/// </value>
- public Type ContractType { get; private set; }
+ public Type? ContractType { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the property, field or parameter will be set
/// Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class.
/// </summary>
public ImportCardinalityMismatchException()
- : this((string)null, (Exception)null)
+ : this((string?)null, (Exception?)null)
{
}
/// <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.Message"/> property to its default value.
/// </param>
- public ImportCardinalityMismatchException(string message)
- : this(message, (Exception)null)
+ public ImportCardinalityMismatchException(string? message)
+ : this(message, (Exception?)null)
{
}
/// <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
/// </param>
- public ImportCardinalityMismatchException(string message, Exception innerException)
+ public ImportCardinalityMismatchException(string? message, Exception? innerException)
: base(message, innerException)
{
}
_exception = exception;
}
- public Exception InnerException
+ public Exception? InnerException
{
get { return _exception.InnerException; }
}
/// </para>
/// </remarks>
public ImportManyAttribute()
- : this((string)null)
+ : this((string?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ImportManyAttribute(Type contractType)
- : this((string)null, contractType)
+ public ImportManyAttribute(Type? contractType)
+ : this((string?)null, contractType)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public ImportManyAttribute(string contractName)
- : this(contractName, (Type)null)
+ public ImportManyAttribute(string? contractName)
+ : this(contractName, (Type?)null)
{
}
- public ImportManyAttribute(string contractName, Type contractType)
+ public ImportManyAttribute(string? contractName, Type? contractType)
{
ContractName = contractName;
ContractType = contractType;
/// A <see cref="string"/> containing the contract name of the exports to import. The
/// default value is an empty string ("").
/// </value>
- public string ContractName { get; private set; }
+ public string? ContractName { get; private set; }
/// <summary>
/// Get the contract type of the export to import.
/// the member that this import is attached to. If the type is <see cref="object"/> then the
/// importer is delaring they can accept any exported type.
/// </value>
- public Type ContractType { get; private set; }
+ public Type? ContractType { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the property or field will be recomposed
/// </para>
/// </remarks>
public InheritedExportAttribute()
- : this((string)null, (Type)null)
+ : this((string?)null, (Type?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public InheritedExportAttribute(Type contractType)
- : this((string)null, contractType)
+ public InheritedExportAttribute(Type? contractType)
+ : this((string?)null, contractType)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public InheritedExportAttribute(string contractName)
- : this(contractName, (Type)null)
+ public InheritedExportAttribute(string? contractName)
+ : this(contractName, (Type?)null)
{
}
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
- public InheritedExportAttribute(string contractName, Type contractType)
+ public InheritedExportAttribute(string? contractName, Type? contractType)
: base(contractName, contractType)
{
}
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition
{
internal static class MetadataServices
{
- public static readonly IDictionary<string, object> EmptyMetadata = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>(0));
+ public static readonly IDictionary<string, object?> EmptyMetadata = new ReadOnlyDictionary<string, object?>(new Dictionary<string, object?>(0));
- public static IDictionary<string, object> AsReadOnly(this IDictionary<string, object> metadata)
+ public static IDictionary<string, object?> AsReadOnly(this IDictionary<string, object?>? metadata)
{
if (metadata == null)
{
return EmptyMetadata;
}
- if (metadata is ReadOnlyDictionary<string, object>)
+ if (metadata is ReadOnlyDictionary<string, object?>)
{
return metadata;
}
- return new ReadOnlyDictionary<string, object>(metadata);
+ return new ReadOnlyDictionary<string, object?>(metadata);
}
- public static T GetValue<T>(this IDictionary<string, object> metadata, string key)
+ [return: MaybeNull]
+ public static T GetValue<T>(this IDictionary<string, object?> metadata, string key)
{
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
- object untypedValue = null;
- if (!metadata.TryGetValue(key, out untypedValue))
+ if (!metadata.TryGetValue(key, out object? untypedValue))
{
- return default(T);
+ return default(T)!;
}
if (untypedValue is T)
}
else
{
- return default(T);
+ return default(T)!;
}
}
}
// }
internal static class MetadataViewGenerator
{
- public delegate object MetadataViewFactory(IDictionary<string, object> metadata);
+ public delegate object MetadataViewFactory(IDictionary<string, object?> metadata);
public const string MetadataViewType = "MetadataViewType";
public const string MetadataItemKey = "MetadataItemKey";
private static readonly Lock _lock = new Lock();
private static readonly Dictionary<Type, MetadataViewFactory> _metadataViewFactories = new Dictionary<Type, MetadataViewFactory>();
private static readonly AssemblyName ProxyAssemblyName = new AssemblyName(string.Format(CultureInfo.InvariantCulture, "MetadataViewProxies_{0}", Guid.NewGuid()));
- private static ModuleBuilder transparentProxyModuleBuilder;
+ private static ModuleBuilder? transparentProxyModuleBuilder;
private static readonly Type[] CtorArgumentTypes = new Type[] { typeof(IDictionary<string, object>) };
- private static readonly MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue");
- private static readonly MethodInfo ObjectGetType = typeof(object).GetMethod("GetType", Type.EmptyTypes);
- private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
+ private static readonly MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue")!;
+ private static readonly MethodInfo ObjectGetType = typeof(object).GetMethod("GetType", Type.EmptyTypes)!;
+ private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!;
// Must be called with _lock held
private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical)
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- MetadataViewFactory metadataViewFactory;
+ MetadataViewFactory? metadataViewFactory;
bool foundMetadataViewFactory;
using (new ReadLock(_lock))
if (!foundMetadataViewFactory)
{
// Try again under a write lock if still none generate the proxy
- Type generatedProxyType = GenerateInterfaceViewProxyType(viewType);
+ Type? generatedProxyType = GenerateInterfaceViewProxyType(viewType);
if (generatedProxyType == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
MetadataViewFactory generatedMetadataViewFactory = (MetadataViewFactory)Delegate.CreateDelegate(
- typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static));
+ typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static)!);
if (generatedMetadataViewFactory == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
}
}
- return metadataViewFactory;
+ return metadataViewFactory!;
}
- public static TMetadataView CreateMetadataView<TMetadataView>(MetadataViewFactory metadataViewFactory, IDictionary<string, object> metadata)
+ public static TMetadataView CreateMetadataView<TMetadataView>(MetadataViewFactory metadataViewFactory, IDictionary<string, object?> metadata)
{
if (metadataViewFactory == null)
{
}
// This must be called with _readerWriterLock held for Write
- private static Type GenerateInterfaceViewProxyType(Type viewType)
+ private static Type? GenerateInterfaceViewProxyType(Type viewType)
{
// View type is an interface let's cook an implementation
- Type proxyType;
+ Type? proxyType;
TypeBuilder proxyTypeBuilder;
Type[] interfaces = { viewType };
bool requiresCritical = false;
string propertyName = propertyInfo.Name;
Type[] propertyTypeArguments = new Type[] { propertyInfo.PropertyType };
- Type[] optionalModifiers = null;
- Type[] requiredModifiers = null;
+ Type[]? optionalModifiers = null;
+ Type[]? requiredModifiers = null;
// PropertyInfo does not support GetOptionalCustomModifiers and GetRequiredCustomModifiers on Silverlight
optionalModifiers = propertyInfo.GetOptionalCustomModifiers();
optionalModifiers,
Type.EmptyTypes, null, null);
- proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod());
+ proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod()!);
ILGenerator getMethodIL = getMethodBuilder.GetILGenerator();
getMethodIL.Emit(OpCodes.Ldarg_0);
getMethodIL.Emit(OpCodes.Ldfld, proxyFieldBuilder);
/// using a generated type.
/// </para>
/// </remarks>
- public MetadataViewImplementationAttribute(Type implementationType)
+ public MetadataViewImplementationAttribute(Type? implementationType)
{
ImplementationType = implementationType;
}
/// <see langword="null"/> which means that the type will be obtained by looking at the type on
/// the member that this export is attached to.
/// </value>
- public Type ImplementationType { get; private set; }
+ public Type? ImplementationType { get; private set; }
}
}
using System.Globalization;
using System.Reflection;
using Microsoft.Internal;
+using System.Diagnostics;
namespace System.ComponentModel.Composition
{
internal static class MetadataViewProvider
{
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
+ public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object?> metadata)
{
if (metadata == null)
{
Type metadataViewType = typeof(TMetadataView);
// If the Metadata dictionary is cast compatible with the passed in type
- if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object>)))
+ if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object?>)))
{
return (TMetadataView)metadata;
}
// otherwise is it a metadata view
else
{
- Type proxyType = null;
- MetadataViewGenerator.MetadataViewFactory metadataViewFactory = null;
+ Type? proxyType = null;
+ MetadataViewGenerator.MetadataViewFactory? metadataViewFactory = null;
if (metadataViewType.IsInterface)
{
if (!metadataViewType.IsAttributeDefined<MetadataViewImplementationAttribute>())
else
{
var implementationAttribute = metadataViewType.GetFirstAttribute<MetadataViewImplementationAttribute>();
+ Debug.Assert(implementationAttribute != null);
proxyType = implementationAttribute.ImplementationType;
if (proxyType == null)
{
throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_MetadataViewImplementationCanNotBeNull,
- metadataViewType.FullName,
- proxyType.FullName));
+ metadataViewType.FullName));
}
else
{
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- return (TMetadataView)proxyType.SafeCreateInstance(metadata);
+ return (TMetadataView)proxyType.SafeCreateInstance(metadata)!;
}
}
catch (MissingMethodException ex)
// Unable to create an Instance of the Metadata view '{0}' because a constructor could not be selected. Ensure that the type implements a constructor which takes an argument of type IDictionary<string, object>.
throw new CompositionContractMismatchException(SR.Format(
SR.CompositionException_MetadataViewInvalidConstructor,
- proxyType.AssemblyQualifiedName), ex);
+ proxyType!.AssemblyQualifiedName), ex);
}
catch (TargetInvocationException ex)
{
//Unwrap known failures that we want to present as CompositionContractMismatchException
if (metadataViewType.IsInterface)
{
- if (ex.InnerException.GetType() == typeof(InvalidCastException))
+ if (ex.InnerException!.GetType() == typeof(InvalidCastException))
{
// Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with the value {2} as type {3} but the view imports it as type {4}.
throw new CompositionContractMismatchException(SR.Format(
/// An <see cref="object"/> containing the metadata value. This can be
/// <see langword="null"/>.
/// </param>
- public PartMetadataAttribute(string name, object value)
+ public PartMetadataAttribute(string? name, object? value)
{
Name = name ?? string.Empty;
Value = value;
/// <value>
/// An <see cref="object"/> containing the metadata value.
/// </value>
- public object Value
+ public object? Value
{
get;
private set;
/// </note>
/// </para>
/// </remarks>
- public virtual IDictionary<string, object> Metadata
+ public virtual IDictionary<string, object?> Metadata
{
get
{
/// <exception cref="ComposablePartException">
/// An error occurred getting the exported value described by the <see cref="ExportDefinition"/>.
/// </exception>
- public abstract object GetExportedValue(ExportDefinition definition);
+ public abstract object? GetExportedValue(ExportDefinition definition);
/// <summary>
/// Sets the import described by the specified definition with the specified exports.
public abstract class ComposablePartCatalog : IEnumerable<ComposablePartDefinition>, IDisposable
{
private bool _isDisposed;
- private volatile IQueryable<ComposablePartDefinition> _queryableParts = null;
+ private volatile IQueryable<ComposablePartDefinition>? _queryableParts = null;
internal static readonly List<Tuple<ComposablePartDefinition, ExportDefinition>> _EmptyExportsList = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
Requires.NotNull(definition, nameof(definition));
- List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
+ List<Tuple<ComposablePartDefinition, ExportDefinition>>? exports = null;
var candidateParts = GetCandidateParts(definition);
if (candidateParts != null)
{
foreach (var part in candidateParts)
{
- Tuple<ComposablePartDefinition, ExportDefinition> singleMatch;
- IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches;
-
- if (part.TryGetExports(definition, out singleMatch, out multipleMatches))
+ if (part.TryGetExports(definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches))
{
exports = exports.FastAppendToListAllowNulls(singleMatch, multipleMatches);
}
return exports ?? _EmptyExportsList;
}
- internal virtual IEnumerable<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition)
+ internal virtual IEnumerable<ComposablePartDefinition>? GetCandidateParts(ImportDefinition definition)
{
return this;
}
using System.Collections.Generic;
using System.Linq;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.Primitives
{
/// </note>
/// </para>
/// </remarks>
- public virtual IDictionary<string, object> Metadata
+ public virtual IDictionary<string, object?> Metadata
{
get { return MetadataServices.EmptyMetadata; }
}
/// </remarks>
public abstract ComposablePart CreatePart();
- internal virtual bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+ internal virtual bool TryGetExports(ImportDefinition definition, [NotNullWhen(true)] out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
{
singleMatch = null;
multipleMatches = null;
- List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
- Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
+ List<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleExports = null;
+ Tuple<ComposablePartDefinition, ExportDefinition>? singleExport = null;
bool matchesFound = false;
foreach (var export in ExportDefinitions)
{
return true;
}
- internal virtual ComposablePartDefinition GetGenericPartDefinition()
+ internal virtual ComposablePartDefinition? GetGenericPartDefinition()
{
return null;
}
[Serializable]
public class ComposablePartException : Exception
{
- private readonly ICompositionElement _element;
+ private readonly ICompositionElement? _element;
/// <summary>
/// Initializes a new instance of the <see cref="ComposablePartException"/> class.
/// </summary>
public ComposablePartException()
- : this((string)null, (ICompositionElement)null, (Exception)null)
+ : this((string?)null, (ICompositionElement?)null, (Exception?)null)
{
}
/// </exception>
protected ComposablePartException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- _element = (ICompositionElement)info.GetValue("Element", typeof(ICompositionElement));
+ _element = (ICompositionElement?)info.GetValue("Element", typeof(ICompositionElement));
}
/// <summary>
/// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.Message"/> property to its default value.
/// </param>
- public ComposablePartException(string message)
- : this(message, (ICompositionElement)null, (Exception)null)
+ public ComposablePartException(string? message)
+ : this(message, (ICompositionElement?)null, (Exception?)null)
{
}
/// the <see cref="ComposablePartException.Element"/> property to
/// <see langword="null"/>.
/// </param>
- public ComposablePartException(string message, ICompositionElement element)
- : this(message, element, (Exception)null)
+ public ComposablePartException(string? message, ICompositionElement? element)
+ : this(message, element, (Exception?)null)
{
}
/// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
/// </param>
- public ComposablePartException(string message, Exception innerException)
- : this(message, (ICompositionElement)null, innerException)
+ public ComposablePartException(string? message, Exception? innerException)
+ : this(message, (ICompositionElement?)null, innerException)
{
}
/// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
/// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
/// </param>
- public ComposablePartException(string message, ICompositionElement element, Exception innerException)
+ public ComposablePartException(string? message, ICompositionElement? element, Exception? innerException)
: base(message, innerException)
{
_element = element;
/// The <see cref="ICompositionElement"/> that is the cause of the
/// <see cref="ComposablePartException"/>. The default is <see langword="null"/>.
/// </value>
- public ICompositionElement Element
+ public ICompositionElement? Element
{
get { return _element; }
}
_exception = exception;
}
- public ICompositionElement Element
+ public ICompositionElement? Element
{
get { return _exception.Element; }
}
- public Exception InnerException
+ public Exception? InnerException
{
get { return _exception.InnerException; }
}
internal class CompositionElement : ICompositionElement
{
private readonly string _displayName;
- private readonly ICompositionElement _origin;
- private readonly object _underlyingObject;
- private static readonly ICompositionElement UnknownOrigin = new CompositionElement(SR.CompositionElement_UnknownOrigin, (ICompositionElement)null);
+ private readonly ICompositionElement? _origin;
+ private readonly object? _underlyingObject;
+ private static readonly ICompositionElement UnknownOrigin = new CompositionElement(SR.CompositionElement_UnknownOrigin, (ICompositionElement?)null);
public CompositionElement(object underlyingObject)
: this(underlyingObject.ToString(), UnknownOrigin)
_underlyingObject = underlyingObject;
}
- public CompositionElement(string displayName, ICompositionElement origin)
+ public CompositionElement(string? displayName, ICompositionElement? origin)
{
_displayName = displayName ?? string.Empty;
_origin = origin;
get { return _displayName; }
}
- public ICompositionElement Origin
+ public ICompositionElement? Origin
{
get { return _origin; }
}
return DisplayName;
}
- public object UnderlyingObject
+ public object? UnderlyingObject
{
get { return _underlyingObject; }
}
get { return _element.DisplayName; }
}
- public ICompositionElement Origin
+ public ICompositionElement? Origin
{
get { return _element.Origin; }
}
- public object UnderlyingObject
+ public object? UnderlyingObject
{
get { return _element.UnderlyingObject; }
}
{
internal static class CompositionElementExtensions
{
- public static ICompositionElement ToSerializableElement(this ICompositionElement element)
+ public static ICompositionElement? ToSerializableElement(this ICompositionElement? element)
{
return SerializableCompositionElement.FromICompositionElement(element);
}
public static ICompositionElement ToElement(this Export export)
{
// First try the export
- ICompositionElement element = export as ICompositionElement;
- if (element != null)
+ if (export is ICompositionElement element)
{
return element;
}
private static string GetDisplayNameCore(object value)
{
- ICompositionElement element = value as ICompositionElement;
- if (element != null)
+ if (value is ICompositionElement element)
{
return element.DisplayName;
}
- return value.ToString();
+ return value.ToString()!;
}
private static ICompositionElement ToElementCore(object value)
{
- ICompositionElement element = value as ICompositionElement;
- if (element != null)
+ if (value is ICompositionElement element)
{
return element;
}
// Unlike contract name, both metadata and required metadata has a sensible default; set it to an empty
// enumerable, so that derived definitions only need to override ContractName by default.
private readonly IEnumerable<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>();
- private Expression<Func<ExportDefinition, bool>> _constraint;
+ private Expression<Func<ExportDefinition, bool>>? _constraint;
private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any;
- private readonly string _requiredTypeIdentity = null;
+ private readonly string? _requiredTypeIdentity = null;
private bool _isRequiredMetadataValidated = false;
/// <summary>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy)
: this(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, MetadataServices.EmptyMetadata)
{
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata)
+ public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
+ ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object?> metadata)
: base(contractName, cardinality, isRecomposable, isPrerequisite, metadata)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
/// on the type that this import expects. If the value is <see langword="null"/> then this import
/// doesn't expect a particular type.
/// </value>
- public virtual string RequiredTypeIdentity
+ public virtual string? RequiredTypeIdentity
{
get { return _requiredTypeIdentity; }
}
{
if (!string.IsNullOrEmpty(RequiredTypeIdentity))
{
- string exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
+ string? exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
if (!StringComparers.ContractName.Equals(RequiredTypeIdentity, exportTypeIdentity))
{
string metadataKey = metadataItem.Key;
Type metadataValueType = metadataItem.Value;
- object metadataValue = null;
- if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue))
+ if (!definition.Metadata.TryGetValue(metadataKey, out object? metadataValue))
{
return false;
}
/// </summary>
public class Export
{
- private readonly ExportDefinition _definition;
- private readonly Func<object> _exportedValueGetter;
+ private readonly ExportDefinition? _definition;
+ private readonly Func<object?>? _exportedValueGetter;
private static readonly object _EmptyValue = new object();
- private volatile object _exportedValue = Export._EmptyValue;
+ private volatile object? _exportedValue = Export._EmptyValue;
/// <summary>
/// Initializes a new instance of the <see cref="Export"/> class.
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// </exception>
- public Export(string contractName, Func<object> exportedValueGetter)
- : this(new ExportDefinition(contractName, (IDictionary<string, object>)null), exportedValueGetter)
+ public Export(string contractName, Func<object?> exportedValueGetter)
+ : this(new ExportDefinition(contractName, (IDictionary<string, object?>?)null), exportedValueGetter)
{
}
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// </exception>
- public Export(string contractName, IDictionary<string, object> metadata, Func<object> exportedValueGetter)
+ public Export(string contractName, IDictionary<string, object?>? metadata, Func<object?> exportedValueGetter)
: this(new ExportDefinition(contractName, metadata), exportedValueGetter)
{
}
/// </para>
/// <paramref name="exportedValueGetter"/> is <see langword="null"/>.
/// </exception>
- public Export(ExportDefinition definition, Func<object> exportedValueGetter)
+ public Export(ExportDefinition definition, Func<object?> exportedValueGetter)
{
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(exportedValueGetter, nameof(exportedValueGetter));
/// of the <see cref="Definition"/> property.
/// </para>
/// </remarks>
- public IDictionary<string, object> Metadata
+ public IDictionary<string, object?> Metadata
{
get
{
/// <exception cref="NotImplementedException">
/// The <see cref="GetExportedValueCore"/> method was not overridden by a derived class.
/// </exception>
- public object Value
+ public object? Value
{
get
{
// more than once, as locking would be required for that. The said locking is problematic, as we can't reliable call 3rd party code under a lock.
if (_exportedValue == Export._EmptyValue)
{
- object exportedValue = GetExportedValueCore();
+ object? exportedValue = GetExportedValueCore();
Interlocked.CompareExchange(ref _exportedValue, exportedValue, Export._EmptyValue);
}
/// </note>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- protected virtual object GetExportedValueCore()
+ protected virtual object? GetExportedValueCore()
{
if (_exportedValueGetter != null)
{
{
// Unlike contract name, metadata has a sensible default; set it to an empty bag,
// so that derived definitions only need to override ContractName by default.
- private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata;
- private readonly string _contractName;
+ private readonly IDictionary<string, object?> _metadata = MetadataServices.EmptyMetadata;
+ private readonly string? _contractName;
/// <summary>
/// Initializes a new instance of the <see cref="ExportDefinition"/> class.
/// <exception cref="ArgumentException">
/// <paramref name="contractName"/> is an empty string ("").
/// </exception>
- public ExportDefinition(string contractName, IDictionary<string, object> metadata)
+ public ExportDefinition(string contractName, IDictionary<string, object?>? metadata)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
/// </note>
/// </para>
/// </remarks>
- public virtual IDictionary<string, object> Metadata
+ public virtual IDictionary<string, object?> Metadata
{
get
{
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public class ExportedDelegate
{
- private readonly object _instance;
- private readonly MethodInfo _method;
+ private readonly object? _instance;
+ private readonly MethodInfo _method = null!;
protected ExportedDelegate() { }
- public ExportedDelegate(object instance, MethodInfo method)
+ public ExportedDelegate(object? instance, MethodInfo method)
{
Requires.NotNull(method, nameof(method));
_method = method;
}
- public virtual Delegate CreateDelegate(Type delegateType)
+ public virtual Delegate? CreateDelegate(Type delegateType)
{
Requires.NotNull(delegateType, nameof(delegateType));
/// <see cref="ICompositionElement"/> originated, or <see langword="null"/>
/// if the <see cref="ICompositionElement"/> is the root composition element.
/// </value>
- ICompositionElement Origin
+ ICompositionElement? Origin
{
get;
}
public class ImportDefinition
{
internal static readonly string EmptyContractName = string.Empty;
- private readonly Expression<Func<ExportDefinition, bool>> _constraint;
+ private readonly Expression<Func<ExportDefinition, bool>>? _constraint;
private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne;
private readonly string _contractName = EmptyContractName;
private readonly bool _isRecomposable;
private readonly bool _isPrerequisite = true;
- private Func<ExportDefinition, bool> _compiledConstraint;
- private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata;
+ private Func<ExportDefinition, bool>? _compiledConstraint;
+ private readonly IDictionary<string, object?> _metadata = MetadataServices.EmptyMetadata;
/// <summary>
/// Initializes a new instance of the <see cref="ImportDefinition"/> class.
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
+ public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
: this(contractName, cardinality, isRecomposable, isPrerequisite, MetadataServices.EmptyMetadata)
{
Requires.NotNull(constraint, nameof(constraint));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata)
+ public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object?>? metadata)
: this(contractName, cardinality, isRecomposable, isPrerequisite, metadata)
{
Requires.NotNull(constraint, nameof(constraint));
_constraint = constraint;
}
- internal ImportDefinition(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata)
+ internal ImportDefinition(string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object?>? metadata)
{
if (
(cardinality != ImportCardinality.ExactlyOne) &&
/// </note>
/// </para>
/// </remarks>
- public virtual IDictionary<string, object> Metadata
+ public virtual IDictionary<string, object?> Metadata
{
get
{
public static ImportDefinition GetProductImportDefinition(this ImportDefinition import)
{
- IPartCreatorImportDefinition partCreatorDefinition = import as IPartCreatorImportDefinition;
-
- if (partCreatorDefinition != null)
+ if (import is IPartCreatorImportDefinition partCreatorDefinition)
{
return partCreatorDefinition.ProductImportDefinition;
}
{
import = import.GetProductImportDefinition();
string contractName = import.ContractName;
- string genericContractName = import.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
- int[] importParametersOrder = import.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+ string? genericContractName = import.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
+ int[]? importParametersOrder = import.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
if (importParametersOrder != null)
{
int partArity = part.Metadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName);
import = import.GetProductImportDefinition();
if (expandGenerics)
{
- Tuple<ComposablePartDefinition, ExportDefinition> singleMatch;
- IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches;
- return part.TryGetExports(import, out singleMatch, out multipleMatches);
+ return part.TryGetExports(import, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches);
}
else
{
private static ImportDefinition TranslateImport(ImportDefinition import, ComposablePartDefinition part)
{
- ContractBasedImportDefinition contractBasedImport = import as ContractBasedImportDefinition;
+ ContractBasedImportDefinition? contractBasedImport = import as ContractBasedImportDefinition;
if (contractBasedImport == null)
{
return import;
}
- int[] importParametersOrder = contractBasedImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+ int[]? importParametersOrder = contractBasedImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
if (importParametersOrder == null)
{
return import;
}
string contractName = GenericServices.GetGenericName(contractBasedImport.ContractName, importParametersOrder, partArity);
- string requiredTypeIdentity = GenericServices.GetGenericName(contractBasedImport.RequiredTypeIdentity, importParametersOrder, partArity);
+ string requiredTypeIdentity = GenericServices.GetGenericName(contractBasedImport.RequiredTypeIdentity!, importParametersOrder, partArity);
return new ContractBasedImportDefinition(
contractName,
requiredTypeIdentity,
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.Primitives
{
internal class SerializableCompositionElement : ICompositionElement
{
private readonly string _displayName;
- private readonly ICompositionElement _origin;
+ private readonly ICompositionElement? _origin;
- public SerializableCompositionElement(string displayName, ICompositionElement origin)
+ public SerializableCompositionElement(string displayName, ICompositionElement? origin)
{
_displayName = displayName;
_origin = origin;
public string DisplayName => _displayName;
- public ICompositionElement Origin => _origin;
+ public ICompositionElement? Origin => _origin;
- public static ICompositionElement FromICompositionElement(ICompositionElement element)
+ [return: NotNullIfNotNull("element")]
+ public static ICompositionElement? FromICompositionElement(ICompositionElement? element)
{
if (element == null)
{
return null;
}
- ICompositionElement origin = FromICompositionElement(element.Origin);
+ ICompositionElement? origin = FromICompositionElement(element.Origin);
// Otherwise, we need to create a serializable wrapper
return new SerializableCompositionElement(element.DisplayName, origin);
{
}
- protected override void ReleaseInstanceIfNecessary(object instance)
+ protected override void ReleaseInstanceIfNecessary(object? instance)
{
- IDisposable disposable = instance as IDisposable;
- if (disposable != null)
+ if (instance is IDisposable disposable)
{
disposable.Dispose();
}
{
T exportedValue;
Action disposeAction;
- IDisposable disposable = null;
+ IDisposable? disposable = null;
- CatalogExportProvider.ScopeFactoryExport scopeFactoryExport = export as CatalogExportProvider.ScopeFactoryExport;
-
- if (scopeFactoryExport != null)
+ if (export is CatalogExportProvider.ScopeFactoryExport scopeFactoryExport)
{
// Scoped PartCreatorExport
Export exportProduct = scopeFactoryExport.CreateExportProduct();
}
else
{
- CatalogExportProvider.FactoryExport factoryExport = export as CatalogExportProvider.FactoryExport;
-
- if (factoryExport != null)
+ if (export is CatalogExportProvider.FactoryExport factoryExport)
{
// PartCreatorExport is the more optimized route
Export exportProduct = factoryExport.CreateExportProduct();
{
internal sealed partial class ExportFactoryCreator
{
- private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
- private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
+ private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!;
+ private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!;
private readonly Type _exportFactoryType;
_exportFactoryType = exportFactoryType;
}
- public Func<Export, object> CreateStronglyTypedExportFactoryFactory(Type exportType, Type metadataViewType)
+ public Func<Export, object> CreateStronglyTypedExportFactoryFactory(Type exportType, Type? metadataViewType)
{
- MethodInfo genericMethod = null;
+ MethodInfo genericMethod;
if (metadataViewType == null)
{
genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType);
var instance = Activator.CreateInstance(constructed, args);
- return instance;
+ return instance!;
}
private object CreateStronglyTypedExportFactoryOfTM<T, M>(Export export)
Func<Tuple<T, Action>> exportLifetimeContextCreator = () => lifetimeContext.GetExportLifetimeContextFromExport<T>(export);
var metadataView = AttributedModelServices.GetMetadataView<M>(export.Metadata);
- object[] args = { exportLifetimeContextCreator, metadataView };
+ object?[] args = { exportLifetimeContextCreator, metadataView };
var instance = Activator.CreateInstance(constructed, args);
- return instance;
+ return instance!;
}
}
{
private readonly ExportDefinition _definition;
private readonly ReflectionMember _member;
- private object _cachedValue = null;
+ private object? _cachedValue = null;
private volatile bool _isValueCached = false;
public ExportingMember(ExportDefinition definition, ReflectionMember member)
get { return _definition; }
}
- public object GetExportedValue(object instance, object @lock)
+ public object? GetExportedValue(object? instance, object @lock)
{
EnsureReadable();
if (!_isValueCached)
{
- object exportedValue;
+ object? exportedValue;
try
{
exportedValue = _member.GetValue(instance);
using System.Globalization;
using System.Linq;
using System.Reflection;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.ReflectionModel
{
return genericSpecialization;
}
- public static IEnumerable<Type> CreateTypeSpecializations(this Type[] types, Type[] specializationTypes)
+ [return: NotNullIfNotNull("types")]
+ public static IEnumerable<Type>? CreateTypeSpecializations(this Type[]? types, Type[] specializationTypes)
{
if (types == null)
{
}
- public static bool CanSpecialize(Type type, IEnumerable<Type> constraints, GenericParameterAttributes attributes)
+ public static bool CanSpecialize(Type? type, IEnumerable<Type>? constraints, GenericParameterAttributes attributes)
{
- return CanSpecialize(type, constraints) && CanSpecialize(type, attributes);
+ return CanSpecialize(type, constraints) && CanSpecialize(type!, attributes);
}
- public static bool CanSpecialize(Type type, IEnumerable<Type> constraintTypes)
+ public static bool CanSpecialize(Type? type, IEnumerable<Type>? constraintTypes)
{
if (constraintTypes == null)
{
using System.Threading;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.ReflectionModel
{
private readonly ReflectionComposablePartDefinition _originalPart;
private readonly Type[] _specialization;
private readonly string[] _specializationIdentities;
- private IEnumerable<ExportDefinition> _exports;
- private IEnumerable<ImportDefinition> _imports;
+ private IEnumerable<ExportDefinition>? _exports;
+ private IEnumerable<ImportDefinition>? _imports;
private readonly Lazy<Type> _lazyPartType;
- private List<LazyMemberInfo> _members;
- private List<Lazy<ParameterInfo>> _parameters;
- private Dictionary<LazyMemberInfo, MemberInfo[]> _membersTable;
- private Dictionary<Lazy<ParameterInfo>, ParameterInfo> _parametersTable;
- private ConstructorInfo _constructor;
+ private List<LazyMemberInfo>? _members;
+ private List<Lazy<ParameterInfo>>? _parameters;
+ private Dictionary<LazyMemberInfo, MemberInfo[]>? _membersTable;
+ private Dictionary<Lazy<ParameterInfo>, ParameterInfo>? _parametersTable;
+ private ConstructorInfo? _constructor;
private readonly object _lock = new object();
public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization)
return _lazyPartType;
}
- public ConstructorInfo GetConstructor()
+ public ConstructorInfo? GetConstructor()
{
if (_constructor == null)
{
- ConstructorInfo genericConstuctor = _originalPartCreationInfo.GetConstructor();
- ConstructorInfo result = null;
+ ConstructorInfo? genericConstuctor = _originalPartCreationInfo.GetConstructor();
+ ConstructorInfo? result = null;
if (genericConstuctor != null)
{
foreach (ConstructorInfo constructor in GetPartType().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
return _constructor;
}
- public IDictionary<string, object> GetMetadata()
+ public IDictionary<string, object?> GetMetadata()
{
- var originalMetadata = new Dictionary<string, object>(_originalPartCreationInfo.GetMetadata(), StringComparers.MetadataKeyNames);
+ var originalMetadata = new Dictionary<string, object?>(_originalPartCreationInfo.GetMetadata()!, StringComparers.MetadataKeyNames);
originalMetadata.Remove(CompositionConstants.IsGenericPartMetadataName);
originalMetadata.Remove(CompositionConstants.GenericPartArityMetadataName);
originalMetadata.Remove(CompositionConstants.GenericParameterConstraintsMetadataName);
PopulateImportsAndExports();
- List<LazyMemberInfo> members = null;
- List<Lazy<ParameterInfo>> parameters = null;
+ List<LazyMemberInfo>? members = null;
+ List<Lazy<ParameterInfo>>? parameters = null;
lock (_lock)
{
if (_membersTable == null)
//
// Get all members that can be of interest and extract their MetadataTokens
//
- Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members);
- Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = BuildParametersTable(parameters);
+ Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members!);
+ Dictionary<Lazy<ParameterInfo>, ParameterInfo>? parametersTable = BuildParametersTable(parameters);
lock (_lock)
{
{
if (genericAccessors[i] != null)
{
- specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]);
+ specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]!);
if (accessors[i] == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
return membersTable;
}
- private Dictionary<Lazy<ParameterInfo>, ParameterInfo> BuildParametersTable(List<Lazy<ParameterInfo>> parameters)
+ [return: NotNullIfNotNull("parameters")]
+ private Dictionary<Lazy<ParameterInfo>, ParameterInfo>? BuildParametersTable(List<Lazy<ParameterInfo>>? parameters)
{
if (parameters != null)
{
Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = new Dictionary<Lazy<ParameterInfo>, ParameterInfo>();
// GENTODO - error case
- ParameterInfo[] constructorParameters = GetConstructor().GetParameters();
+ ParameterInfo[] constructorParameters = GetConstructor()!.GetParameters();
foreach (var lazyParameter in parameters)
{
parametersTable[lazyParameter] = constructorParameters[lazyParameter.Value.Position];
foreach (ImportDefinition originalImport in _originalPartCreationInfo.GetImports())
{
- ReflectionImportDefinition reflectionImport = originalImport as ReflectionImportDefinition;
+ ReflectionImportDefinition? reflectionImport = originalImport as ReflectionImportDefinition;
if (reflectionImport == null)
{
// we always ignore these
bool isExportFactory = false;
ContractBasedImportDefinition productImport = reflectionImport;
- IPartCreatorImportDefinition exportFactoryImportDefinition = reflectionImport as IPartCreatorImportDefinition;
- if (exportFactoryImportDefinition != null)
+ if (reflectionImport is IPartCreatorImportDefinition exportFactoryImportDefinition)
{
productImport = exportFactoryImportDefinition.ProductImportDefinition;
isExportFactory = true;
}
string contractName = Translate(productImport.ContractName);
- string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity);
- IDictionary<string, object> metadata = TranslateImportMetadata(productImport);
+ string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity!);
+ IDictionary<string, object?> metadata = TranslateImportMetadata(productImport);
- ReflectionMemberImportDefinition memberImport = reflectionImport as ReflectionMemberImportDefinition;
- ImportDefinition import = null;
- if (memberImport != null)
+ ImportDefinition? import = null;
+ if (reflectionImport is ReflectionMemberImportDefinition memberImport)
{
LazyMemberInfo lazyMember = memberImport.ImportingLazyMember;
LazyMemberInfo importingMember = new LazyMemberInfo(lazyMember.MemberType, () => GetAccessors(lazyMember));
}
else
{
- ReflectionParameterImportDefinition parameterImport = reflectionImport as ReflectionParameterImportDefinition;
+ ReflectionParameterImportDefinition? parameterImport = reflectionImport as ReflectionParameterImportDefinition;
if (parameterImport == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
foreach (ExportDefinition originalExport in _originalPartCreationInfo.GetExports())
{
- ReflectionMemberExportDefinition reflectionExport = originalExport as ReflectionMemberExportDefinition;
+ ReflectionMemberExportDefinition? reflectionExport = originalExport as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
// we always ignore these
public ExportDefinition TranslateExpot(ReflectionMemberExportDefinition reflectionExport, List<LazyMemberInfo> members)
{
- ExportDefinition export = null;
+ ExportDefinition? export = null;
LazyMemberInfo lazyMember = reflectionExport.ExportingLazyMember;
var capturedLazyMember = lazyMember;
var capturedReflectionExport = reflectionExport;
string contractName = Translate(reflectionExport.ContractName, reflectionExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
LazyMemberInfo exportingMember = new LazyMemberInfo(capturedLazyMember.MemberType, () => GetAccessors(capturedLazyMember));
- Lazy<IDictionary<string, object>> lazyMetadata = new Lazy<IDictionary<string, object>>(() => TranslateExportMetadata(capturedReflectionExport));
+ Lazy<IDictionary<string, object?>> lazyMetadata = new Lazy<IDictionary<string, object?>>(() => TranslateExportMetadata(capturedReflectionExport));
export = new ReflectionMemberExportDefinition(
exportingMember,
return export;
}
- private string Translate(string originalValue, int[] genericParametersOrder)
+ private string Translate(string originalValue, int[]? genericParametersOrder)
{
if (genericParametersOrder != null)
{
return string.Format(CultureInfo.InvariantCulture, originalValue, _specializationIdentities);
}
- private IDictionary<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
+ private IDictionary<string, object?> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
{
- int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+ int[]? importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
if (importParametersOrder != null)
{
- Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames);
+ Dictionary<string, object?> metadata = new Dictionary<string, object?>(originalImport.Metadata, StringComparers.MetadataKeyNames);
// Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization
metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, _specialization.Length);
}
}
- private IDictionary<string, object> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport)
+ private IDictionary<string, object?> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport)
{
- Dictionary<string, object> metadata = new Dictionary<string, object>(originalExport.Metadata, StringComparers.MetadataKeyNames);
+ Dictionary<string, object?> metadata = new Dictionary<string, object?>(originalExport.Metadata, StringComparers.MetadataKeyNames);
- string exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
+ string? exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
if (!string.IsNullOrEmpty(exportTypeIdentity))
{
metadata[CompositionConstants.ExportTypeIdentityMetadataName] = Translate(exportTypeIdentity, originalExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
public IEnumerable<ExportDefinition> GetExports()
{
PopulateImportsAndExports();
- return _exports;
+ return _exports!;
}
public IEnumerable<ImportDefinition> GetImports()
{
PopulateImportsAndExports();
- return _imports;
+ return _imports!;
}
public bool IsDisposalRequired
get { return Translate(_originalPartCreationInfo.DisplayName); }
}
- public ICompositionElement Origin
+ public ICompositionElement? Origin
{
get { return _originalPartCreationInfo.Origin; }
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
- GenericSpecializationPartCreationInfo that = obj as GenericSpecializationPartCreationInfo;
- if (that == null)
- {
- return false;
- }
-
- return (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) &&
+ return obj is GenericSpecializationPartCreationInfo that && (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) &&
(_specialization.IsArrayEqual(that._specialization));
}
return _originalPartCreationInfo.GetHashCode();
}
- public static bool CanSpecialize(IDictionary<string, object> partMetadata, Type[] specialization)
+ public static bool CanSpecialize(IDictionary<string, object?> partMetadata, Type[] specialization)
{
int partArity = partMetadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName);
return false;
}
- object[] genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName);
- GenericParameterAttributes[] genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(CompositionConstants.GenericParameterAttributesMetadataName);
+ object[]? genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName);
+ GenericParameterAttributes[]? genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(CompositionConstants.GenericParameterAttributesMetadataName);
// if no constraints and attributes been specifed, anything can be created
if ((genericParameterConstraints == null) && (genericParameterAttributes == null))
{
if (!GenericServices.CanSpecialize(
specialization[i],
- (genericParameterConstraints[i] as Type[]).CreateTypeSpecializations(specialization),
- genericParameterAttributes[i]))
+ (genericParameterConstraints![i] as Type[]).CreateTypeSpecializations(specialization),
+ genericParameterAttributes![i]))
{
return false;
}
{
Type GetPartType();
Lazy<Type> GetLazyPartType();
- ConstructorInfo GetConstructor();
- IDictionary<string, object> GetMetadata();
+ ConstructorInfo? GetConstructor();
+ IDictionary<string, object?>? GetMetadata();
IEnumerable<ExportDefinition> GetExports();
IEnumerable<ImportDefinition> GetImports();
bool IsDisposalRequired { get; }
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using Microsoft.Internal.Collections;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Composition.ReflectionModel
{
private readonly Type _type;
private readonly bool _isAssignableCollectionType;
- private Type _contractType;
- private Func<Export, object> _castSingleValue;
+ private Type _contractType = null!; // Initialized in Initialize()
+ private Func<Export, object>? _castSingleValue;
private readonly bool _isOpenGeneric = false;
[ThreadStatic]
- internal static Dictionary<Type, Func<Export, object>> _castSingleValueCache;
+ internal static Dictionary<Type, Func<Export, object>>? _castSingleValueCache;
private static Dictionary<Type, Func<Export, object>> CastSingleValueCache
{
get { return _isAssignableCollectionType; }
}
- public Type ElementType { get; private set; }
+ public Type? ElementType { get; private set; }
public Type ActualType
{
public Type ContractType { get { return _contractType; } }
- public Func<Export, object> CastExport
+ public Func<Export, object>? CastExport
{
get
{
}
}
- public Type MetadataViewType { get; private set; }
+ public Type? MetadataViewType { get; private set; }
private Type CheckForCollection(Type type)
{
return type;
}
- private static bool IsGenericDescendentOf(Type type, Type baseGenericTypeDefinition)
+ private static bool IsGenericDescendentOf(Type? type, Type baseGenericTypeDefinition)
{
if (type == typeof(object) || type == null)
{
return (genericType == LazyOfTType) || (genericType == LazyOfTMType);
}
- private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, out Func<Export, object> castFunction)
+ private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, [NotNullWhen(true)] out Func<Export, object>? castFunction)
{
castFunction = null;
}
else
{
- throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName);
+ throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName!);
}
}
get { return _importType; }
}
- public object CastExportsToImportType(Export[] exports)
+ public object? CastExportsToImportType(Export[] exports)
{
if (Definition.Cardinality == ImportCardinality.ZeroOrMore)
{
for (int i = 0; i < array.Length; i++)
{
- object value = CastSingleExportToImportType(elementType, exports[i]);
+ object? value = CastSingleExportToImportType(elementType, exports[i]);
array.SetValue(value, i);
}
return array;
}
- private object CastExportsToSingleImportType(Export[] exports)
+ private object? CastExportsToSingleImportType(Export[] exports)
{
if (exports == null)
{
return CastSingleExportToImportType(ImportType.ActualType, exports[0]);
}
- private object CastSingleExportToImportType(Type type, Export export)
+ private object? CastSingleExportToImportType(Type type, Export export)
{
if (ImportType.CastExport != null)
{
return Cast(type, export);
}
- private object Cast(Type type, Export export)
+ private object? Cast(Type type, Export export)
{
- object value = export.Value;
+ object? value = export.Value;
- object result;
- if (!ContractServices.TryCast(type, value, out result))
+ if (!ContractServices.TryCast(type, value, out object? result))
{
throw new ComposablePartException(
SR.Format(
_member = member;
}
- public void SetExportedValue(object instance, object value)
+ public void SetExportedValue(object? instance, object value)
{
if (RequiresCollectionNormalization())
{
return true;
}
- private void SetSingleMemberValue(object instance, object value)
+ private void SetSingleMemberValue(object? instance, object? value)
{
EnsureWritable();
}
}
- private void SetCollectionMemberValue(object instance, IEnumerable values)
+ private void SetCollectionMemberValue(object? instance, IEnumerable values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
- ICollection<object> collection = null;
- Type itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType);
+ ICollection<object>? collection = null;
+ Type? itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType);
if (itemType != null)
{
collection = GetNormalizedCollection(itemType, instance);
}
EnsureCollectionIsWritable(collection);
- PopulateCollection(collection, values);
+ PopulateCollection(collection!, values);
}
- private ICollection<object> GetNormalizedCollection(Type itemType, object instance)
+ private ICollection<object> GetNormalizedCollection(Type itemType, object? instance)
{
if (itemType == null)
{
throw new ArgumentNullException(nameof(itemType));
}
- object collectionObject = null;
+ object? collectionObject = null;
if (_member.CanRead)
{
if (collectionObject == null)
{
- ConstructorInfo constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes);
+ ConstructorInfo? constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes);
// If it contains a default public constructor create a new instance.
if (constructor != null)
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- private void EnsureCollectionIsWritable(ICollection<object> collection)
+ private void EnsureCollectionIsWritable(ICollection<object>? collection)
{
bool isReadOnly = true;
SR.Format(
SR.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
_member.GetDisplayName(),
- collection.GetType().FullName),
+ collection!.GetType().FullName),
Definition.ToElement(),
exception);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- private void PopulateCollection(ICollection<object> collection, IEnumerable values)
+ private void PopulateCollection(ICollection<object?> collection, IEnumerable values)
{
if (collection == null)
{
exception);
}
- foreach (object value in values)
+ foreach (object? value in values)
{
try
{
public struct LazyMemberInfo
{
private readonly MemberTypes _memberType;
- private MemberInfo[] _accessors;
- private readonly Func<MemberInfo[]> _accessorsCreator;
+ private MemberInfo?[]? _accessors;
+ private readonly Func<MemberInfo[]>? _accessorsCreator;
public LazyMemberInfo(MemberInfo member)
{
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- _accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) };
+ _accessors = new MemberInfo?[] { property.GetGetMethod(true), property.GetSetMethod(true) };
break;
case MemberTypes.Event:
EventInfo event_ = (EventInfo)member;
- _accessors = new MemberInfo[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) };
+ _accessors = new MemberInfo?[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) };
break;
default:
_accessors = new MemberInfo[] { member };
_accessors = accessors;
}
- return _accessors;
+ return _accessors!;
}
public override int GetHashCode()
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- return MemberType.GetHashCode() ^ _accessors[0].GetHashCode();
+ return MemberType.GetHashCode() ^ _accessors[0]!.GetHashCode(); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
}
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
- LazyMemberInfo that = (LazyMemberInfo)obj;
+ LazyMemberInfo that = (LazyMemberInfo)obj!;
// Difefrent member types mean different members
if (_memberType != that._memberType)
internal class PartCreatorExportDefinition : ExportDefinition
{
private readonly ExportDefinition _productDefinition;
- private IDictionary<string, object> _metadata;
+ private IDictionary<string, object?>? _metadata;
public PartCreatorExportDefinition(ExportDefinition productDefinition)
: base()
}
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
if (_metadata == null)
{
- var metadata = new Dictionary<string, object>(_productDefinition.Metadata);
+ var metadata = new Dictionary<string, object?>(_productDefinition.Metadata);
metadata[CompositionConstants.ExportTypeIdentityMetadataName] = CompositionConstants.PartCreatorTypeIdentity;
metadata[CompositionConstants.ProductDefinitionMetadataName] = _productDefinition;
internal static bool IsProductConstraintSatisfiedBy(ImportDefinition productImportDefinition, ExportDefinition exportDefinition)
{
- object productValue = null;
- if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ProductDefinitionMetadataName, out productValue))
+ if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ProductDefinitionMetadataName, out object? productValue))
{
- ExportDefinition productDefinition = productValue as ExportDefinition;
-
- if (productDefinition != null)
+ if (productValue is ExportDefinition productDefinition)
{
return productImportDefinition.IsConstraintSatisfiedBy(productDefinition);
}
public PartCreatorMemberImportDefinition(
LazyMemberInfo importingLazyMember,
- ICompositionElement origin,
+ ICompositionElement? origin,
ContractBasedImportDefinition productImportDefinition)
: base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, productImportDefinition.RequiredCreationPolicy, MetadataServices.EmptyMetadata, origin)
public PartCreatorParameterImportDefinition(
Lazy<ParameterInfo> importingLazyParameter,
- ICompositionElement origin,
+ ICompositionElement? origin,
ContractBasedImportDefinition productImportDefinition)
: base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, MetadataServices.EmptyMetadata, origin)
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
+using System.Diagnostics;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePart : ComposablePart, ICompositionElement
{
private readonly ReflectionComposablePartDefinition _definition;
- private volatile Dictionary<ImportDefinition, object> _importValues = null;
- private volatile Dictionary<ImportDefinition, ImportingItem> _importsCache = null;
- private volatile Dictionary<int, ExportingMember> _exportsCache = null;
+ private volatile Dictionary<ImportDefinition, object?>? _importValues = null;
+ private volatile Dictionary<ImportDefinition, ImportingItem>? _importsCache = null;
+ private volatile Dictionary<int, ExportingMember>? _exportsCache = null;
private volatile bool _invokeImportsSatisfied = true;
private bool _initialCompositionComplete = false;
- private volatile object _cachedInstance;
+ private volatile object? _cachedInstance;
private readonly object _lock = new object();
public ReflectionComposablePart(ReflectionComposablePartDefinition definition)
EnsureRunning();
}
- protected virtual void ReleaseInstanceIfNecessary(object instance)
+ protected virtual void ReleaseInstanceIfNecessary(object? instance)
{
}
- private Dictionary<ImportDefinition, object> ImportValues
+ private Dictionary<ImportDefinition, object?> ImportValues
{
get
{
value = _importValues;
if (value == null)
{
- value = new Dictionary<ImportDefinition, object>();
+ value = new Dictionary<ImportDefinition, object?>();
_importValues = value;
}
}
}
}
- protected object CachedInstance
+ protected object? CachedInstance
{
get
{
}
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
// This is the ONLY method which is not executed under the ImportEngine composition lock.
// We need to protect all state that is accesses
- public override object GetExportedValue(ExportDefinition definition)
+ public override object? GetExportedValue(ExportDefinition definition)
{
RequiresRunning();
// given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed
// access to _instance
Requires.NotNull(definition, nameof(definition));
- ExportingMember member = null;
+ ExportingMember? member = null;
lock (_lock)
{
member = GetExportingMemberFromDefinition(definition);
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(exports, nameof(exports));
- ImportingItem item = GetImportingItemFromDefinition(definition);
+ ImportingItem? item = GetImportingItemFromDefinition(definition);
if (item == null)
{
throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart(nameof(definition));
return GetDisplayName();
}
- private object GetExportedValue(ExportingMember member)
+ private object? GetExportedValue(ExportingMember member)
{
- object instance = null;
+ object? instance = null;
if (member.RequiresInstance)
{ // Only activate the instance if we actually need to
private void SetImport(ImportingItem item, Export[] exports)
{
- object value = item.CastExportsToImportType(exports);
+ object? value = item.CastExportsToImportType(exports);
lock (_lock)
{
}
}
- private object GetInstanceActivatingIfNeeded()
+ private object? GetInstanceActivatingIfNeeded()
{
var cachedInstance = _cachedInstance;
}
else
{
- ConstructorInfo constructor = null;
- object[] arguments = null;
+ ConstructorInfo? constructor = null;
+ object?[]? arguments = null;
// determine whether activation is required, and collect necessary information for activation
// we need to do that under a lock
lock (_lock)
}
// create instance outside of the lock
- object createdInstance = CreateInstance(constructor, arguments);
+ object? createdInstance = CreateInstance(constructor, arguments);
SetPrerequisiteImports();
}
// if the instance has been already set
- if (createdInstance == null)
+ if (createdInstance != null)
{
ReleaseInstanceIfNecessary(createdInstance);
}
return _cachedInstance;
}
- private object[] GetConstructorArguments()
+ private object?[] GetConstructorArguments()
{
ReflectionParameterImportDefinition[] parameterImports = ImportDefinitions.OfType<ReflectionParameterImportDefinition>().ToArray();
- object[] arguments = new object[parameterImports.Length];
+ object?[] arguments = new object?[parameterImports.Length];
UseImportedValues(
parameterImports,
// need activation.
return ExportDefinitions.Any(definition =>
{
- ExportingMember member = GetExportingMemberFromDefinition(definition);
-
+ ExportingMember? member = GetExportingMemberFromDefinition(definition);
+ Debug.Assert(member != null);
return member.RequiresInstance;
});
}
}
}
- private object CreateInstance(ConstructorInfo constructor, object[] arguments)
+ private object CreateInstance(ConstructorInfo constructor, object?[] arguments)
{
- Exception exception = null;
- object instance = null;
+ Exception? exception = null;
+ object instance = null!;
try
{
{
ImportingMember importMember = (ImportingMember)import;
- object instance = GetInstanceActivatingIfNeeded();
+ object? instance = GetInstanceActivatingIfNeeded();
importMember.SetExportedValue(instance, value);
}
foreach (var definition in definitions)
{
- ImportingItem import = GetImportingItemFromDefinition(definition);
+ ImportingItem? import = GetImportingItemFromDefinition(definition);
+ Debug.Assert(import != null);
- object value;
- if (!TryGetImportValue(definition, out value))
+ if (!TryGetImportValue(definition, out object? value))
{
if (!errorIfMissing)
{
}
}
- useImportValue(import, definition, value);
+ useImportValue(import, definition, value!);
}
result.ThrowOnErrors();
}
- private bool TryGetImportValue(ImportDefinition definition, out object value)
+ private bool TryGetImportValue(ImportDefinition definition, out object? value)
{
lock (_lock)
{
{
if (_invokeImportsSatisfied)
{
- IPartImportsSatisfiedNotification notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification;
+ IPartImportsSatisfiedNotification? notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification;
lock (_lock)
{
}
// this is always called under a lock
- private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition)
+ private ExportingMember? GetExportingMemberFromDefinition(ExportDefinition definition)
{
- ExportingMember result;
- ReflectionMemberExportDefinition reflectionExport = definition as ReflectionMemberExportDefinition;
+ ReflectionMemberExportDefinition? reflectionExport = definition as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
return null;
{
_exportsCache = new Dictionary<int, ExportingMember>();
}
- if (!_exportsCache.TryGetValue(exportIndex, out result))
+ if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result))
{
result = GetExportingMember(definition);
if (result != null)
return result;
}
- private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition)
+ private ImportingItem? GetImportingItemFromDefinition(ImportDefinition definition)
{
- ImportingItem result;
- if (!ImportsCache.TryGetValue(definition, out result))
+ if (!ImportsCache.TryGetValue(definition, out ImportingItem? result))
{
result = GetImportingItem(definition);
if (result != null)
return result;
}
- private static ImportingItem GetImportingItem(ImportDefinition definition)
+ private static ImportingItem? GetImportingItem(ImportDefinition definition)
{
- ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition;
- if (reflectionDefinition != null)
+ if (definition is ReflectionImportDefinition reflectionDefinition)
{
return reflectionDefinition.ToImportingItem();
}
return null;
}
- private static ExportingMember GetExportingMember(ExportDefinition definition)
+ private static ExportingMember? GetExportingMember(ExportDefinition definition)
{
- ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition;
- if (exportDefinition != null)
+ if (definition is ReflectionMemberExportDefinition exportDefinition)
{
return exportDefinition.ToExportingMember();
}
{
private readonly IReflectionPartCreationInfo _creationInfo;
- private volatile ImportDefinition[] _imports;
- private volatile ExportDefinition[] _exports;
- private volatile IDictionary<string, object> _metadata;
- private volatile ConstructorInfo _constructor;
+ private volatile ImportDefinition[]? _imports;
+ private volatile ExportDefinition[]? _exports;
+ private volatile IDictionary<string, object?>? _metadata;
+ private volatile ConstructorInfo? _constructor;
private readonly object _lock = new object();
public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
return _creationInfo.GetLazyPartType();
}
- public ConstructorInfo GetConstructor()
+ public ConstructorInfo? GetConstructor()
{
if (_constructor == null)
{
- ConstructorInfo constructor = _creationInfo.GetConstructor();
+ ConstructorInfo? constructor = _creationInfo.GetConstructor();
lock (_lock)
{
if (_constructor == null)
}
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
if (_metadata == null)
{
- IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly();
+ IDictionary<string, object?> metadata = _creationInfo.GetMetadata().AsReadOnly();
lock (_lock)
{
if (_metadata == null)
}
}
- internal override ComposablePartDefinition GetGenericPartDefinition()
+ internal override ComposablePartDefinition? GetGenericPartDefinition()
{
- GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo;
- if (genericCreationInfo != null)
+ if (_creationInfo is GenericSpecializationPartCreationInfo genericCreationInfo)
{
return genericCreationInfo.OriginalPart;
}
return null;
}
- internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+ internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
{
if (this.IsGeneric())
{
singleMatch = null;
multipleMatches = null;
- List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
+ List<Tuple<ComposablePartDefinition, ExportDefinition>>? exports = null;
var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(CompositionConstants.GenericParametersMetadataName) : null;
// if and only if generic parameters have been supplied can we attempt to "close" the generic
if (genericParameters != null)
{
- Type[] genericTypeParameters = null;
// we only understand types
- if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters))
+ if (TryGetGenericTypeParameters(genericParameters, out Type?[]? genericTypeParameters))
{
- HashSet<ComposablePartDefinition> candidates = null;
- ComposablePartDefinition candidatePart = null;
- ComposablePartDefinition previousPart = null;
+ HashSet<ComposablePartDefinition>? candidates = null;
+ ComposablePartDefinition? previousPart = null;
// go through all orders of generic parameters that part exports allows
- foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters))
+ foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters!))
{
- if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart))
+ if (TryMakeGenericPartDefinition(candidateParameters, out ComposablePartDefinition? candidatePart))
{
bool alreadyProcessed = false;
if (candidates == null)
}
if (!alreadyProcessed)
{
- Tuple<ComposablePartDefinition, ExportDefinition> candidateSingleMatch;
- IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches;
- if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches))
+ if (candidatePart.TryGetExports(definition, out Tuple<ComposablePartDefinition, ExportDefinition>? candidateSingleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? candidateMultipleMatches))
{
exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches);
}
}
// Optimised for local as array case
- private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+ private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
{
singleMatch = null;
multipleMatches = null;
- List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
- Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
+ List<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleExports = null;
+ Tuple<ComposablePartDefinition, ExportDefinition>? singleExport = null;
bool matchesFound = false;
foreach (var export in ExportDefinitionsInternal)
}
- private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
+ private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, [NotNullWhen(true)] out Type?[]? genericTypeParameters)
{
genericTypeParameters = genericParameters as Type[];
if (genericTypeParameters == null)
return true;
}
- internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition)
+ internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, [NotNullWhen(true)] out ComposablePartDefinition? genericPartDefinition)
{
genericPartDefinition = null;
get { return _creationInfo.DisplayName; }
}
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return _creationInfo.Origin; }
}
return _creationInfo.DisplayName;
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (_creationInfo.IsIdentityComparison)
{
}
else
{
- ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition;
- if (that == null)
- {
- return false;
- }
-
- return _creationInfo.Equals(that._creationInfo);
+ return obj is ReflectionComposablePartDefinition that && _creationInfo.Equals(that._creationInfo);
}
}
if (member.MemberType == MemberTypes.Property)
{
- PropertyInfo property = member as PropertyInfo;
+ PropertyInfo? property = member as PropertyInfo;
if (property == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- MemberInfo[] accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) };
+ MemberInfo[] accessors = new MemberInfo[] { property.GetGetMethod(true)!, property.GetSetMethod(true)! };
return new LazyMemberInfo(MemberTypes.Property, accessors);
}
else
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- ReflectionWritableMember reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember;
+ ReflectionWritableMember? reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember;
if (reflectionMember == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
throw new ArgumentNullException(nameof(property));
}
- return CreateReflectionProperty(property.GetGetMethod(true), property.GetSetMethod(true));
+ return CreateReflectionProperty(property.GetGetMethod(true)!, property.GetSetMethod(true)!);
}
public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, MethodInfo setMethod)
get { return ReflectionItemType.Field; }
}
- public override object GetValue(object instance)
+ public override object? GetValue(object? instance)
{
return UndelyingField.SafeGetValue(instance);
}
- public override void SetValue(object instance, object value)
+ public override void SetValue(object? instance, object? value)
{
UndelyingField.SafeSetValue(instance, value);
}
{
internal abstract class ReflectionImportDefinition : ContractBasedImportDefinition, ICompositionElement
{
- private readonly ICompositionElement _origin;
+ private readonly ICompositionElement? _origin;
public ReflectionImportDefinition(
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
bool isRecomposable,
bool isPrerequisite,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
- ICompositionElement origin)
+ IDictionary<string, object?> metadata,
+ ICompositionElement? origin)
: base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata)
{
_origin = origin;
get { return GetDisplayName(); }
}
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return _origin; }
}
{
internal abstract class ReflectionItem
{
- public abstract string Name { get; }
+ public abstract string? Name { get; }
public abstract string GetDisplayName();
public abstract Type ReturnType { get; }
public abstract ReflectionItemType ItemType { get; }
public Type DeclaringType
{
- get { return UnderlyingMember.DeclaringType; }
+ get { return UnderlyingMember.DeclaringType!; }
}
public override string Name
public abstract MemberInfo UnderlyingMember { get; }
- public abstract object GetValue(object instance);
+ public abstract object? GetValue(object? instance);
}
}
{
private readonly LazyMemberInfo _member;
private readonly ExportDefinition _exportDefinition;
- private readonly ICompositionElement _origin;
- private IDictionary<string, object> _metadata;
+ private readonly ICompositionElement? _origin;
+ private IDictionary<string, object?>? _metadata;
- public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement origin)
+ public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement? origin)
{
if (exportDefinition == null)
{
get { return _member; }
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
get { return GetDisplayName(); }
}
- ICompositionElement ICompositionElement.Origin
+ ICompositionElement? ICompositionElement.Origin
{
get { return _origin; }
}
public ReflectionMemberImportDefinition(
LazyMemberInfo importingLazyMember,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
bool isRecomposable,
bool isPrerequisite,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
- ICompositionElement origin)
+ IDictionary<string, object?> metadata,
+ ICompositionElement? origin)
: base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin)
{
if (contractName == null)
get { return ReflectionItemType.Method; }
}
- public override object GetValue(object instance)
+ public override object GetValue(object? instance)
{
return SafeCreateExportedDelegate(instance, _method);
}
- private static ExportedDelegate SafeCreateExportedDelegate(object instance, MethodInfo method)
+ private static ExportedDelegate SafeCreateExportedDelegate(object? instance, MethodInfo method)
{
return new ExportedDelegate(instance, method);
}
{
Requires.NotNull(partDefinition, nameof(partDefinition));
- ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
+ ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
if (reflectionPartDefinition == null)
{
throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
{
Requires.NotNull(partDefinition, nameof(partDefinition));
- ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
+ ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
if (reflectionPartDefinition == null)
{
throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
{
Requires.NotNull(exportDefinition, nameof(exportDefinition));
- ReflectionMemberExportDefinition reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition;
+ ReflectionMemberExportDefinition? reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition;
if (reflectionExportDefinition == null)
{
throw new ArgumentException(
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- ReflectionMemberImportDefinition reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition;
+ ReflectionMemberImportDefinition? reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition;
if (reflectionMemberImportDefinition == null)
{
throw new ArgumentException(
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition;
+ ReflectionParameterImportDefinition? reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition;
if (reflectionParameterImportDefinition == null)
{
throw new ArgumentException(
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition;
+ ReflectionImportDefinition? reflectionImportDefinition = importDefinition as ReflectionImportDefinition;
if (reflectionImportDefinition == null)
{
throw new ArgumentException(
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition;
+ IPartCreatorImportDefinition? partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition;
if (partCreatorImportDefinition == null)
{
throw new ArgumentException(
public static ComposablePartDefinition CreatePartDefinition(
Lazy<Type> partType,
bool isDisposalRequired,
- Lazy<IEnumerable<ImportDefinition>> imports,
- Lazy<IEnumerable<ExportDefinition>> exports,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
+ Lazy<IEnumerable<ImportDefinition>>? imports,
+ Lazy<IEnumerable<ExportDefinition>>? exports,
+ Lazy<IDictionary<string, object?>>? metadata,
+ ICompositionElement? origin)
{
Requires.NotNull(partType, nameof(partType));
public static ExportDefinition CreateExportDefinition(
LazyMemberInfo exportingMember,
string contractName,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
+ Lazy<IDictionary<string, object?>> metadata,
+ ICompositionElement? origin)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
Requires.IsInMembertypeSet(exportingMember.MemberType, nameof(exportingMember), MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method);
public static ContractBasedImportDefinition CreateImportDefinition(
LazyMemberInfo importingMember,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
bool isRecomposable,
CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
+ ICompositionElement? origin)
{
return CreateImportDefinition(importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin);
}
public static ContractBasedImportDefinition CreateImportDefinition(
LazyMemberInfo importingMember,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
bool isRecomposable,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
+ IDictionary<string, object?> metadata,
bool isExportFactory,
- ICompositionElement origin)
+ ICompositionElement? origin)
{
return CreateImportDefinition(
importingMember,
public static ContractBasedImportDefinition CreateImportDefinition(
LazyMemberInfo importingMember,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
bool isRecomposable,
bool isPreRequisite,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
+ IDictionary<string, object?> metadata,
bool isExportFactory,
- ICompositionElement origin)
+ ICompositionElement? origin)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
Requires.IsInMembertypeSet(importingMember.MemberType, nameof(importingMember), MemberTypes.Property | MemberTypes.Field);
public static ContractBasedImportDefinition CreateImportDefinition(
Lazy<ParameterInfo> parameter,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
+ ICompositionElement? origin)
{
return CreateImportDefinition(parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin);
}
public static ContractBasedImportDefinition CreateImportDefinition(
Lazy<ParameterInfo> parameter,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
+ IDictionary<string, object?> metadata,
bool isExportFactory,
- ICompositionElement origin)
+ ICompositionElement? origin)
{
Requires.NotNull(parameter, nameof(parameter));
Requires.NotNullOrEmpty(contractName, nameof(contractName));
}
}
- public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable<Type> genericParameters, out ComposablePartDefinition specialization)
+ public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable<Type> genericParameters, [NotNullWhen(true)] out ComposablePartDefinition? specialization)
{
Requires.NotNull(partDefinition, nameof(partDefinition));
specialization = null;
- ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
+ ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
if (reflectionPartDefinition == null)
{
throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType());
internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo
{
private readonly Lazy<Type> _partType;
- private readonly Lazy<IEnumerable<ImportDefinition>> _imports;
- private readonly Lazy<IEnumerable<ExportDefinition>> _exports;
- private readonly Lazy<IDictionary<string, object>> _metadata;
- private readonly ICompositionElement _origin;
- private ConstructorInfo _constructor;
+ private readonly Lazy<IEnumerable<ImportDefinition>>? _imports;
+ private readonly Lazy<IEnumerable<ExportDefinition>>? _exports;
+ private readonly Lazy<IDictionary<string, object?>>? _metadata;
+ private readonly ICompositionElement? _origin;
+ private ConstructorInfo? _constructor;
private readonly bool _isDisposalRequired;
public ReflectionPartCreationInfo(
Lazy<Type> partType,
bool isDisposalRequired,
- Lazy<IEnumerable<ImportDefinition>> imports,
- Lazy<IEnumerable<ExportDefinition>> exports,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
+ Lazy<IEnumerable<ImportDefinition>>? imports,
+ Lazy<IEnumerable<ExportDefinition>>? exports,
+ Lazy<IDictionary<string, object?>>? metadata,
+ ICompositionElement? origin)
{
if (partType == null)
{
return _partType;
}
- public ConstructorInfo GetConstructor()
+ public ConstructorInfo? GetConstructor()
{
if (_constructor == null)
{
- ConstructorInfo[] constructors = null;
+ ConstructorInfo[]? constructors = null;
constructors = GetImports()
.OfType<ReflectionParameterImportDefinition>()
.Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member)
}
}
- public IDictionary<string, object> GetMetadata()
+ public IDictionary<string, object?>? GetMetadata()
{
return (_metadata != null) ? _metadata.Value : null;
}
foreach (ExportDefinition export in exports)
{
- ReflectionMemberExportDefinition reflectionExport = export as ReflectionMemberExportDefinition;
+ ReflectionMemberExportDefinition? reflectionExport = export as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
throw new InvalidOperationException(
foreach (ImportDefinition import in imports)
{
- ReflectionImportDefinition reflectionImport = import as ReflectionImportDefinition;
+ ReflectionImportDefinition? reflectionImport = import as ReflectionImportDefinition;
if (reflectionImport == null)
{
throw new InvalidOperationException(
get { return GetPartType().GetDisplayName(); }
}
- public ICompositionElement Origin
+ public ICompositionElement? Origin
{
get { return _origin; }
}
internal class LazyExportDefinition : ExportDefinition
{
- private readonly Lazy<IDictionary<string, object>> _metadata;
+ private readonly Lazy<IDictionary<string, object?>> _metadata;
- public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object>> metadata)
- : base(contractName, (IDictionary<string, object>)null)
+ public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object?>> metadata)
+ : base(contractName, (IDictionary<string, object?>?)null)
{
_metadata = metadata;
}
- public override IDictionary<string, object> Metadata
+ public override IDictionary<string, object?> Metadata
{
get
{
get { return _parameter; }
}
- public override string Name
+ public override string? Name
{
get { return UnderlyingParameter.Name; }
}
public ReflectionParameterImportDefinition(
Lazy<ParameterInfo> importingLazyParameter,
string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+ string? requiredTypeIdentity,
+ IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
ImportCardinality cardinality,
CreationPolicy requiredCreationPolicy,
- IDictionary<string, object> metadata,
- ICompositionElement origin)
+ IDictionary<string, object?> metadata,
+ ICompositionElement? origin)
: base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin)
{
if (importingLazyParameter == null)
internal class ReflectionProperty : ReflectionWritableMember
{
- private readonly MethodInfo _getMethod;
- private readonly MethodInfo _setMethod;
+ private readonly MethodInfo? _getMethod;
+ private readonly MethodInfo? _setMethod;
- public ReflectionProperty(MethodInfo getMethod, MethodInfo setMethod)
+ public ReflectionProperty(MethodInfo? getMethod, MethodInfo? setMethod)
{
if (getMethod == null && setMethod == null)
{
public override MemberInfo UnderlyingMember
{
- get { return UnderlyingGetMethod ?? UnderlyingSetMethod; }
+ get { return UnderlyingGetMethod ?? UnderlyingSetMethod!; }
}
public override bool CanRead
get { return UnderlyingSetMethod != null; }
}
- public MethodInfo UnderlyingGetMethod
+ public MethodInfo? UnderlyingGetMethod
{
get { return _getMethod; }
}
- public MethodInfo UnderlyingSetMethod
+ public MethodInfo? UnderlyingSetMethod
{
get { return _setMethod; }
}
{
get
{
- MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod;
+ MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod!;
string name = method.Name;
{
get
{
- MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod;
+ MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod!;
return !method.IsStatic;
}
return UnderlyingGetMethod.ReturnType;
}
- ParameterInfo[] parameters = UnderlyingSetMethod.GetParameters();
+ ParameterInfo[] parameters = UnderlyingSetMethod!.GetParameters();
if (parameters.Length == 0)
{
get { return ReflectionItemType.Property; }
}
- public override object GetValue(object instance)
+ public override object? GetValue(object? instance)
{
if (_getMethod == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- return UnderlyingGetMethod.SafeInvoke(instance);
+ return UnderlyingGetMethod!.SafeInvoke(instance);
}
- public override void SetValue(object instance, object value)
+ public override void SetValue(object? instance, object? value)
{
if (_setMethod == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- UnderlyingSetMethod.SafeInvoke(instance, value);
+ UnderlyingSetMethod!.SafeInvoke(instance, value);
}
}
get { return ReflectionItemType.Type; }
}
- public override object GetValue(object instance)
+ public override object? GetValue(object? instance)
{
return instance;
}
get;
}
- public abstract void SetValue(object instance, object value);
+ public abstract void SetValue(object? instance, object? value);
}
}