1

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?

Tomas
  • 17,551
  • 43
  • 152
  • 257

1 Answers1

1

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)
    {
    }
}
qujck
  • 14,388
  • 4
  • 45
  • 74
  • I get exception when remove InjectionConstructor. System.InvalidOperationException: The current type, System.Collections.Generic.IEnumerable`1[PC.Domain.Interfaces.IMetadataItem], is an interface and cannot be constructed. Are you missing a type mapping? – Tomas Sep 27 '18 at 10:40
  • @Tomas what version of Unity are you using? – qujck Sep 27 '18 at 10:41
  • I use 4.1 version, should I upgrade to 5? – Tomas Sep 27 '18 at 10:43
  • @Tomas I've tested it with 5. Before you do upgrade, older versions of Unity didn't internally understand `IEnumerable<>`, you could try `IMetadataItem[]` in the constructor of `MetadataService` – qujck Sep 27 '18 at 10:46
  • That did the trick! When I was coding I have used IMetadataItem[] but Resharper suggested refactoring to IEnumerable. I didn't thought that it would make difference. – Tomas Sep 27 '18 at 10:49