Reputation: 18097
I have several classes which derived from interface
public interface IMetadataItem
{
Do();
}
public class MyClass1 : IMetadataItem
{
public void Do()
{
}
}
public class MyClass2 : IMetadataItem
{
public void Do()
{
}
}
I would like to bind these classes of IMetadataItem interface to constructor of another class
public class MetadataService: IMetadataService
{
public MetadataService(IEnumerable<IMetadataItem> metadataItems)
{
//metadataItems always has zero(0) items
}
}
Unfortunately I always get empty IEnumerable list.
The Unity config look like
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().Where(type => typeof(IMetadataItem).IsAssignableFrom(type)),
WithMappings.FromAllInterfaces,
WithName.TypeName,
WithLifetime.ContainerControlled);
container.RegisterType<IMetadataService, Services.MetadataService>(new ContainerControlledLifetimeManager(),
new InjectionConstructor(new ResolvedArrayParameter<IMetadataItem>()) );
Any idea what I am doing wrong?
Upvotes: 1
Views: 1070
Reputation: 14580
For Unity v5:
You can remove the 2nd parameter InjectionConstructor
from RegisterType
container.RegisterType<IMetadataService, MetadataService>(
new ContainerControlledLifetimeManager());
For v4:
Unity does not internally understand IEnumerable<>
(see here) so you will need to change the constructor to take an array instead of an enumerable
public class MetadataService: IMetadataService
{
public MetadataService(IMetadataItem[] metadataItems)
{
}
}
Upvotes: 1