Skip to content

Commit c04f3b5

Browse files
committed
Fix support for multiple [Export("contract")] in MEF
When using MEF attributes, we were not considering each export attribute individually like we do for `[Service]`. We now have parity.
1 parent 49f8267 commit c04f3b5

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

src/DependencyInjection.Tests/CompositionTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,19 @@ public void ResolvesDependency()
6262

6363
Assert.Same(singleton, instance.Singleton);
6464
}
65+
66+
[Fact]
67+
public void RegisterKeyedService()
68+
{
69+
var collection = new ServiceCollection();
70+
collection.AddServices();
71+
var services = collection.BuildServiceProvider();
72+
73+
var first = services.GetRequiredKeyedService<SingletonService>("foo");
74+
var second = services.GetRequiredKeyedService<SingletonService>("foo");
75+
76+
Assert.Same(first, second);
77+
}
6578
}
6679

6780
public interface ICompositionSingleton { }
@@ -70,6 +83,7 @@ public interface ICompositionTransient { }
7083
[Shared]
7184
[Export]
7285
[Export(typeof(ICompositionSingleton))]
86+
[Export("foo")]
7387
public class SingletonService : ICompositionSingleton
7488
{
7589
}

src/DependencyInjection/IncrementalGenerator.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ bool IsExport(AttributeData attr)
9797
lifetime = (int)serviceAttr.ConstructorArguments[0].Value!;
9898
}
9999
}
100-
else
100+
else if (IsExport(attr))
101101
{
102102
// In NuGet MEF, [Shared] makes exports singleton
103103
if (attrs.Any(a => a.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::System.Composition.SharedAttribute"))
@@ -116,11 +116,10 @@ bool IsExport(AttributeData attr)
116116
}
117117

118118
// Consider the [Export(contractName)] as a keyed service with the contract name as the key.
119-
if (attrs.FirstOrDefault(IsExport) is { } export &&
120-
export.ConstructorArguments.Length > 0 &&
121-
export.ConstructorArguments[0].Kind == TypedConstantKind.Primitive)
119+
if (attr.ConstructorArguments.Length > 0 &&
120+
attr.ConstructorArguments[0].Kind == TypedConstantKind.Primitive)
122121
{
123-
key = export.ConstructorArguments[0];
122+
key = attr.ConstructorArguments[0];
124123
}
125124
}
126125

src/DependencyInjection/Properties/launchSettings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"profiles": {
33
"Tests": {
44
"commandName": "DebugRoslynComponent",
5-
"targetProject": "..\\DependencyInjection.Attributed.Tests\\Attributed.Tests.csproj"
5+
"targetProject": "..\\DependencyInjection.Tests\\DependencyInjection.Tests.csproj"
66
},
77
"Console": {
88
"commandName": "DebugRoslynComponent",

0 commit comments

Comments
 (0)