-
Notifications
You must be signed in to change notification settings - Fork 33
Metadata
Ian Johnson edited this page Jul 2, 2018
·
3 revisions
Sometimes it's useful to resolve metadata along with your dependency, Grace provides a Meta<T>
class. The following data is provided as part of the Metadata property
- Type that is being activated
- Types that this strategy is exported as (including keyed interfaces)
- Dictionary of metadata items
Below are two unit tests that illustrate how to use metadata
[Fact]
public void Meta_Matches()
{
var container = new DependencyInjectionContainer();
container.Configure(
c => c.Export<BasicService>().As<IBasicService>().WithMetadata("Hello", "World"));
var meta = container.Locate<Meta<IBasicService>>();
Assert.NotNull(meta);
Assert.True(meta.Metadata.MetadataMatches("Hello", "World"));
}
[Fact]
public void Meta_Enumerable()
{
var container = new DependencyInjectionContainer();
container.Configure(c =>
{
c.Export<MultipleService1>().As<IMultipleService>().WithMetadata("Key", 1);
c.Export<MultipleService2>().As<IMultipleService>().WithMetadata("Key", 2);
c.Export<MultipleService3>().As<IMultipleService>().WithMetadata("Key", 3);
c.Export<MultipleService4>().As<IMultipleService>().WithMetadata("Key", 4);
c.Export<MultipleService5>().As<IMultipleService>().WithMetadata("Key", 5);
});
var multipleServices =
container.Locate<IEnumerable<Meta<IMultipleService>>>().ToArray();
Assert.Equal(5, multipleServices.Length);
Assert.Equal(1, multipleServices[0].Metadata["Key"]);
Assert.IsType<MultipleService1>(multipleServices[0].Value);
Assert.Equal(2, multipleServices[1].Metadata["Key"]);
Assert.IsType<MultipleService2>(multipleServices[1].Value);
Assert.Equal(3, multipleServices[2].Metadata["Key"]);
Assert.IsType<MultipleService3>(multipleServices[2].Value);
Assert.Equal(4, multipleServices[3].Metadata["Key"]);
Assert.IsType<MultipleService4>(multipleServices[3].Value);
Assert.Equal(5, multipleServices[4].Metadata["Key"]);
Assert.IsType<MultipleService5>(multipleServices[4].Value);
}