diff --git a/src/DependencyInjection.Tests/CompositionTests.cs b/src/DependencyInjection.Tests/CompositionTests.cs index a07deed..5f3d8a1 100644 --- a/src/DependencyInjection.Tests/CompositionTests.cs +++ b/src/DependencyInjection.Tests/CompositionTests.cs @@ -62,6 +62,19 @@ public void ResolvesDependency() Assert.Same(singleton, instance.Singleton); } + + [Fact] + public void RegisterKeyedService() + { + var collection = new ServiceCollection(); + collection.AddServices(); + var services = collection.BuildServiceProvider(); + + var first = services.GetRequiredKeyedService("foo"); + var second = services.GetRequiredKeyedService("foo"); + + Assert.Same(first, second); + } } public interface ICompositionSingleton { } @@ -70,6 +83,7 @@ public interface ICompositionTransient { } [Shared] [Export] [Export(typeof(ICompositionSingleton))] +[Export("foo")] public class SingletonService : ICompositionSingleton { } diff --git a/src/DependencyInjection/IncrementalGenerator.cs b/src/DependencyInjection/IncrementalGenerator.cs index 4b8f0ad..58e3386 100644 --- a/src/DependencyInjection/IncrementalGenerator.cs +++ b/src/DependencyInjection/IncrementalGenerator.cs @@ -97,7 +97,7 @@ bool IsExport(AttributeData attr) lifetime = (int)serviceAttr.ConstructorArguments[0].Value!; } } - else + else if (IsExport(attr)) { // In NuGet MEF, [Shared] makes exports singleton if (attrs.Any(a => a.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::System.Composition.SharedAttribute")) @@ -116,11 +116,10 @@ bool IsExport(AttributeData attr) } // Consider the [Export(contractName)] as a keyed service with the contract name as the key. - if (attrs.FirstOrDefault(IsExport) is { } export && - export.ConstructorArguments.Length > 0 && - export.ConstructorArguments[0].Kind == TypedConstantKind.Primitive) + if (attr.ConstructorArguments.Length > 0 && + attr.ConstructorArguments[0].Kind == TypedConstantKind.Primitive) { - key = export.ConstructorArguments[0]; + key = attr.ConstructorArguments[0]; } } diff --git a/src/DependencyInjection/Properties/launchSettings.json b/src/DependencyInjection/Properties/launchSettings.json index 94ce90f..3e64e72 100644 --- a/src/DependencyInjection/Properties/launchSettings.json +++ b/src/DependencyInjection/Properties/launchSettings.json @@ -2,7 +2,7 @@ "profiles": { "Tests": { "commandName": "DebugRoslynComponent", - "targetProject": "..\\DependencyInjection.Attributed.Tests\\Attributed.Tests.csproj" + "targetProject": "..\\DependencyInjection.Tests\\DependencyInjection.Tests.csproj" }, "Console": { "commandName": "DebugRoslynComponent",