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?

2
  • Hi friend, How many item in the array you want to pass? Commented Sep 27, 2018 at 8:02
  • It would be around 15 items. Commented Sep 27, 2018 at 8:03

1 Answer 1

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)
    {
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

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 what version of Unity are you using?
I use 4.1 version, should I upgrade to 5?
@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
That did the trick! When I was coding I have used IMetadataItem[] but Resharper suggested refactoring to IEnumerable<IMetadataItem>. I didn't thought that it would make difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.