Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/DependencyInjection.Tests/CompositionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SingletonService>("foo");
var second = services.GetRequiredKeyedService<SingletonService>("foo");

Assert.Same(first, second);
}
}

public interface ICompositionSingleton { }
Expand All @@ -70,6 +83,7 @@ public interface ICompositionTransient { }
[Shared]
[Export]
[Export(typeof(ICompositionSingleton))]
[Export("foo")]
public class SingletonService : ICompositionSingleton
{
}
Expand Down
9 changes: 4 additions & 5 deletions src/DependencyInjection/IncrementalGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand All @@ -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];
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"Tests": {
"commandName": "DebugRoslynComponent",
"targetProject": "..\\DependencyInjection.Attributed.Tests\\Attributed.Tests.csproj"
"targetProject": "..\\DependencyInjection.Tests\\DependencyInjection.Tests.csproj"
},
"Console": {
"commandName": "DebugRoslynComponent",
Expand Down