Skip to content

Commit

Permalink
Merge pull request #29 from autofac/feature/autofac-8
Browse files Browse the repository at this point in the history
Update to Autofac 8.
  • Loading branch information
tillig authored Mar 7, 2024
2 parents 05de15e + 5bac5d0 commit 5c72269
Show file tree
Hide file tree
Showing 18 changed files with 91 additions and 148 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ csharp_indent_switch_labels = true
csharp_indent_labels = one_less_than_current

; Modifier preferences
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:warning

; Avoid this. unless absolutely necessary
dotnet_style_qualification_for_field = false:suggestion
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ publish/
*.pubxml

# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
packages/

# Windows Azure Build Output
Expand Down
3 changes: 1 addition & 2 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"recommendations": [
"formulahendry.dotnet-test-explorer",
"ms-dotnettools.csharp",
"ms-dotnettools.csdevkit",
"editorconfig.editorconfig",
"davidanson.vscode-markdownlint"
]
Expand Down
7 changes: 3 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@
"cref",
"inheritdoc",
"langword",
"netstandard",
"paramref",
"resx",
"typeparam",
"typeparamref",
"xunit"
],
"dotnet-test-explorer.testProjectPath": "test/**/*Test.csproj",
"explorer.fileNesting.patterns": {
"*.resx": "$(capture).*.resx, $(capture).Designer.cs"
"*.resx": "$(capture).*.resx, $(capture).designer.cs, $(capture).designer.vb"
},
"omnisharp.enableEditorConfigSupport": true,
"omnisharp.enableRoslynAnalyzers": true
"omnisharp.enableEditorConfigSupport": true
}
4 changes: 2 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
image: Ubuntu

version: 6.1.0.{build}
version: 7.0.0.{build}

dotnet_csproj:
version_prefix: "6.1.0"
version_prefix: "7.0.0"
patch: true
file: 'src\**\*.csproj'

Expand Down
14 changes: 12 additions & 2 deletions build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,19 @@ try {

if ($env:CI -eq "true") {
# Generate Coverage Report
Write-Message "Downloading and verifying Codecov Uploader"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri https://keybase.io/codecovsecurity/pgp_keys.asc -OutFile codecov.asc
gpg --no-default-keyring --keyring trustedkeys.gpg --import codecov.asc
Invoke-WebRequest -Uri https://uploader.codecov.io/latest/linux/codecov -Outfile codecov
Invoke-WebRequest -Uri https://uploader.codecov.io/latest/linux/codecov.SHA256SUM -Outfile codecov.SHA256SUM
Invoke-WebRequest -Uri https://uploader.codecov.io/latest/linux/codecov.SHA256SUM.sig -Outfile codecov.SHA256SUM.sig
gpgv codecov.SHA256SUM.sig codecov.SHA256SUM
shasum -a 256 -c codecov.SHA256SUM
chmod +x codecov

Write-Message "Generating Codecov Report"
Invoke-WebRequest -Uri 'https://codecov.io/bash' -OutFile codecov.sh
& bash codecov.sh -f "artifacts/coverage/*/coverage*.info"
& ./codecov -f "artifacts/coverage/*/coverage*.info"
}

# Finished
Expand Down
10 changes: 10 additions & 0 deletions build/Analyzers.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,16 @@
<Rules AnalyzerId="Microsoft.Usage" RuleNamespace="Microsoft.Usage">
<!-- Implement standard exception constructors - not all of the exception constructors (e.g., parameterless) are desired in our system. -->
<Rule Id="CA1032" Action="None" />
<!-- Use ArgumentNullException.ThrowIfNull - this isn't available until we stop targeting netstandard. -->
<Rule Id="CA1510" Action="None" />
<!-- Use ArgumentOutOfRangeException.ThrowIfNegative - this isn't available until we stop targeting anything below net8.0. -->
<Rule Id="CA1512" Action="None" />
<!-- Use ObjectDisposedException.ThrowIf - this isn't available until we stop targeting anything below net8.0. -->
<Rule Id="CA1513" Action="None" />
<!-- Change names to avoid reserved word overlaps (e.g., Delegate, GetType, etc.) - too many of these in the public API, we'd break if we fixed it. -->
<Rule Id="CA1716" Action="None" />
<!-- Cache a CompositeFormat object for use in String.Format - this isn't available until we stop targeting netstandard, and we only String.Format when throwing exceptions so the work/complexity isn't justified to increase perf just for those situations. -->
<Rule Id="CA1863" Action="None" />
<!-- Implement serialization constructors - false positive when building .NET Core -->
<Rule Id="CA2229" Action="None" />
<!-- Mark ISerializable types with SerializableAttribute - false positive when building .NET Core -->
Expand All @@ -28,6 +36,8 @@
<Rule Id="SA1203" Action="None" />
<!-- Enforce order of static vs. non-static members -->
<Rule Id="SA1204" Action="None" />
<!-- Modifiers are not ordered - .editorconfig handles this -->
<Rule Id="SA1206" Action="None" />
<!-- Enforce order of readonly vs. non-readonly members -->
<Rule Id="SA1214" Action="None" />
<!-- Fields can't start with underscore -->
Expand Down
4 changes: 4 additions & 0 deletions build/Test.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
<Rule Id="CA1816" Action="None" />
<!-- Mark members static - test methods may not access member data but also can't be static. -->
<Rule Id="CA1822" Action="None" />
<!-- Seal internal types - performance isn't an issue in test libraries. -->
<Rule Id="CA1852" Action="None" />
<!-- Do not directly await a task - this is for libraries rather than test code. -->
<Rule Id="CA2007" Action="None" />
<!-- Implement serialization constructors - false positive when building .NET Core. -->
Expand All @@ -38,6 +40,8 @@
<Rule Id="SA1203" Action="None" />
<!-- Enforce order of static vs. non-static members -->
<Rule Id="SA1204" Action="None" />
<!-- Modifiers are not ordered - .editorconfig handles this -->
<Rule Id="SA1206" Action="None" />
<!-- Enforce order of readonly vs. non-readonly members -->
<Rule Id="SA1214" Action="None" />
<!-- Fields can't start with underscore -->
Expand Down
9 changes: 7 additions & 2 deletions global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
{
"sdk": {
"version": "6.0.300",
"version": "8.0.201",
"rollForward": "latestFeature"
}
},

"additionalSdks": [
"6.0.419",
"7.0.406"
]
}
60 changes: 22 additions & 38 deletions src/Autofac.Integration.Mef/Autofac.Integration.Mef.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
<SignAssembly>true</SignAssembly>
<NeutralLanguage>en-US</NeutralLanguage>
<!-- Frameworks and language features -->
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TargetFrameworks>net8.0;net7.0;net6.0;netstandard2.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<CodeAnalysisRuleSet>../../build/Analyzers.ruleset</CodeAnalysisRuleSet>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Packaging -->
Expand All @@ -37,12 +38,19 @@
<EmbedAllSources>true</EmbedAllSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!-- OmniSharp/VS Code resource generation -->
<CoreCompileDependsOn>PrepareResources;$(CompileDependsOn)</CoreCompileDependsOn>
</PropertyGroup>

<ItemGroup>
<Using Include="System.Diagnostics.CodeAnalysis" />
</ItemGroup>

<!-- Disable nullability warnings in netstandard2.0 -->
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<NoWarn>$(NoWarn);8600;8601;8602;8603;8604</NoWarn>
</PropertyGroup>

<ItemGroup>
<None Include="..\..\build\icon.png" Pack="true" PackagePath="\" />
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
Expand All @@ -53,64 +61,40 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="6.4.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" Condition="Exists('$(MSBuildThisFileDirectory)../../.git')">
<PackageReference Include="Autofac" Version="8.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" Condition="Exists('$(MSBuildThisFileDirectory)../../.git')">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.406">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="System.ComponentModel.Composition" Version="4.5.0" />
<PackageReference Include="System.ComponentModel.Composition" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<!--
Magic embedded resource incantation based on https://github.com/dotnet/msbuild/issues/4751
<ItemDefinitionGroup>
<EmbeddedResource>
<Generator>MSBuild:Compile</Generator>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedFileName>$(IntermediateOutputPath)%(Filename).Designer.cs</StronglyTypedFileName>
<StronglyTypedClassName>%(Filename)</StronglyTypedClassName>
</EmbeddedResource>
</ItemDefinitionGroup>

The EmbeddedResource entry seems to add the Designer files to Compile, so
if you don't first remove them from Compile you get warnings about
double-including source.
-->
<Compile Remove="**/*.Designer.cs" />
<ItemGroup>
<EmbeddedResource Update="ContractBasedServiceResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>ContractBasedServiceResources.Designer.cs</LastGenOutput>
<StronglyTypedFileName>ContractBasedServiceResources.Designer.cs</StronglyTypedFileName>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedNamespace>Autofac.Integration.Mef</StronglyTypedNamespace>
<StronglyTypedClassName>ContractBasedServiceResources</StronglyTypedClassName>
</EmbeddedResource>
<EmbeddedResource Update="LazyWithMetadataRegistrationSourceResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>LazyWithMetadataRegistrationSourceResources.Designer.cs</LastGenOutput>
<StronglyTypedFileName>LazyWithMetadataRegistrationSourceResources.Designer.cs</StronglyTypedFileName>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedNamespace>Autofac.Integration.Mef</StronglyTypedNamespace>
<StronglyTypedClassName>LazyWithMetadataRegistrationSourceResources</StronglyTypedClassName>
</EmbeddedResource>
<EmbeddedResource Update="StronglyTypedMetadataRegistrationSourceResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>StronglyTypedMetadataRegistrationSourceResources.Designer.cs</LastGenOutput>
<StronglyTypedFileName>StronglyTypedMetadataRegistrationSourceResources.Designer.cs</StronglyTypedFileName>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedNamespace>Autofac.Integration.Mef</StronglyTypedNamespace>
<StronglyTypedClassName>StronglyTypedMetadataRegistrationSourceResources</StronglyTypedClassName>
</EmbeddedResource>
<EmbeddedResource Update="RegistrationExtensionsResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>RegistrationExtensionsResources.Designer.cs</LastGenOutput>
<StronglyTypedFileName>RegistrationExtensionsResources.Designer.cs</StronglyTypedFileName>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedNamespace>Autofac.Integration.Mef</StronglyTypedNamespace>
<StronglyTypedClassName>RegistrationExtensionsResources</StronglyTypedClassName>
</EmbeddedResource>
<EmbeddedResource Update="Util\ReflectionExtensionsResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>ReflectionExtensionsResources.Designer.cs</LastGenOutput>
<StronglyTypedFileName>Util\ReflectionExtensionsResources.Designer.cs</StronglyTypedFileName>
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
<StronglyTypedNamespace>Autofac.Integration.Mef.Util</StronglyTypedNamespace>
<StronglyTypedClassName>ReflectionExtensionsResources</StronglyTypedClassName>
</EmbeddedResource>
</ItemGroup>

Expand Down
1 change: 1 addition & 0 deletions src/Autofac.Integration.Mef/ContractBasedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public override bool Equals(object? obj)
/// <returns>
/// A hash code for the current <see cref="object"/>.
/// </returns>
[SuppressMessage("CA1307", "CA1307", Justification = "netstandard does not have a string comparison overload for GetHashCode.")]
public override int GetHashCode()
{
return ContractName.GetHashCode() ^ ExportTypeIdentity.GetHashCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Autofac.Integration.Mef;
/// </remarks>
internal class LazyWithMetadataRegistrationSource : IRegistrationSource
{
private static readonly MethodInfo CreateLazyRegistrationMethod = typeof(LazyWithMetadataRegistrationSource).GetMethod("CreateLazyRegistration", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly MethodInfo CreateLazyRegistrationMethod = typeof(LazyWithMetadataRegistrationSource).GetMethod(nameof(CreateLazyRegistration), BindingFlags.Static | BindingFlags.NonPublic)!;

private delegate IComponentRegistration RegistrationCreator(Service service, ServiceRegistration valueRegistration);

Expand Down
32 changes: 16 additions & 16 deletions src/Autofac.Integration.Mef/RegistrationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ public static class RegistrationExtensions
/// Reference to the internal <see cref="Type"/> for <c>System.ComponentModel.Composition.ContractNameServices</c>,
/// which is responsible for mapping types to MEF contract names.
/// </summary>
private static readonly Type ContractNameServices = typeof(ExportAttribute).Assembly.GetType("System.ComponentModel.Composition.ContractNameServices", true);
private static readonly Type ContractNameServices = typeof(ExportAttribute).Assembly.GetType("System.ComponentModel.Composition.ContractNameServices", true)!;

/// <summary>
/// Reference to the property <c>System.ComponentModel.Composition.ContractNameServices.TypeIdentityCache</c>,
/// which holds the dictionary of <see cref="Type"/> to <see cref="string"/> contract name mappings.
/// </summary>
private static readonly PropertyInfo TypeIdentityCache = ContractNameServices.GetProperty("TypeIdentityCache", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.NonPublic);
private static readonly PropertyInfo TypeIdentityCache = ContractNameServices.GetProperty("TypeIdentityCache", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.NonPublic) ?? throw new InvalidOperationException("ContractNameServices.TypeIdentityCache not found.");

/// <summary>
/// Expose the registered service to MEF parts as an export.
Expand Down Expand Up @@ -297,7 +297,7 @@ private static void AttachExport(IComponentRegistryBuilder registry, IComponentR
registry.Register(rb.CreateRegistration());
}

private static IEnumerable<ServiceRegistration> ComponentsForContract(this IComponentContext context, ContractBasedImportDefinition definition, ContractBasedService contractService)
private static List<ServiceRegistration> ComponentsForContract(this IComponentContext context, ContractBasedImportDefinition definition, ContractBasedService contractService)
{
var componentsForContract = context
.ComponentRegistry
Expand Down Expand Up @@ -334,15 +334,15 @@ private static IEnumerable<Service> DefaultExposedServicesMapper(ExportDefinitio

private static Type FindType(string exportTypeIdentity)
{
var cache = (Dictionary<Type, string>)TypeIdentityCache.GetValue(null, null);
var cache = (Dictionary<Type, string>)TypeIdentityCache.GetValue(null, null)!;
return cache.FirstOrDefault(kvp => kvp.Value == exportTypeIdentity).Key;
}

private static string GetTypeIdentity(ExportDefinition exportDef)
{
if (exportDef.Metadata.TryGetValue(CompositionConstants.ExportTypeIdentityMetadataName, out object typeIdentity))
if (exportDef.Metadata.TryGetValue(CompositionConstants.ExportTypeIdentityMetadataName, out var typeIdentity))
{
return (string)typeIdentity;
return typeIdentity!.ToString()!;
}

return string.Empty;
Expand All @@ -358,14 +358,14 @@ private static bool IsSharedInstance(ExportDefinition export)
return IsSharedInstance(export.Metadata);
}

private static bool IsSharedInstance(IDictionary<string, object> metadata)
private static bool IsSharedInstance(IDictionary<string, object?> metadata)
{
if (metadata != null)
{
if (metadata.TryGetValue(CompositionConstants.PartCreationPolicyMetadataName, out object pcp))
if (metadata.TryGetValue(CompositionConstants.PartCreationPolicyMetadataName, out var pcp))
{
// Here we use the MEF default of Shared, but using the Autofac default may make more sense.
if (pcp != null && (CreationPolicy)pcp == CreationPolicy.NonShared)
if (pcp is CreationPolicy policy && policy == CreationPolicy.NonShared)
{
return false;
}
Expand Down Expand Up @@ -410,7 +410,7 @@ private static void ProcessExportDefinition(ContainerBuilder builder, Func<Expor

if (additionalServices.Length > 0)
{
var additionalRegistration = builder.Register(c => ((Export)c.ResolveService(exportId)).Value)
var additionalRegistration = builder.Register(c => ((Export)c.ResolveService(exportId)).Value!)
.As(additionalServices)
.ExternallyOwned()
.WithMetadata(exportDef.Metadata);
Expand Down Expand Up @@ -508,29 +508,29 @@ private static IEnumerable<Export> ResolveExports(this IComponentContext context
{
if (definition.TryGetLazyType(out var resultType, out var lazyType) && context.TryResolve(resultType, out var resolved))
{
var valueProperty = lazyType.GetProperty("Value");
var metaProperty = lazyType.GetProperty("Metadata");
var valueProperty = lazyType.GetProperty("Value")!;
var metaProperty = lazyType.GetProperty("Metadata")!;
if (resolved is IEnumerable enumerable)
{
return enumerable
.Cast<object>()
.Select(
r => new Export(
definition.ContractName,
metaProperty.GetValue(r) as IDictionary<string, object>,
metaProperty.GetValue(r) as IDictionary<string, object?>,
() => valueProperty.GetValue(r)));
}

return new Export[]
{
new Export(
definition.ContractName,
metaProperty.GetValue(resolved) as IDictionary<string, object>,
metaProperty.GetValue(resolved) as IDictionary<string, object?>,
() => valueProperty.GetValue(resolved)),
};
}

var contractService = new ContractBasedService(definition.ContractName, definition.RequiredTypeIdentity);
var contractService = new ContractBasedService(definition.ContractName, definition.RequiredTypeIdentity!);

var componentsForContract = context.ComponentsForContract(definition, contractService);

Expand Down Expand Up @@ -599,7 +599,7 @@ private static bool TryMapService(ExportDefinition ed, [NotNullWhen(true)] out S
return true;
}

var et = FindType((string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]);
var et = FindType((string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]!);
if (et != null)
{
service = new KeyedService(ed.ContractName, et);
Expand Down
Loading

0 comments on commit 5c72269

Please sign in to comment.