I'm looking for a way to stop Autofac from automatically filling an IEnumerable<> in my constructor.
For example, I have a class called School with the following constructors
public School(string name) {...}
public School(string name, IEnumerable<IStudent> students) {...}
You can use the first constructor to create the School object then use a AddStudent method to add the students to the school.
You can use the second constructor to create a School and pass in a collection of students to be added when the School object is constructed.
If I create Func<string, ISchool> schoolFactory, then call schoolFactory.Invoke("Test"), Autofac will use the second constructor and will automatically create a new Student object.
The IStudent interface and Student classes are registered with Autofac and the Student class has a default constructor. The default constructor is there because it's used in our UI when a user adds a new Student. The new Student is created with a blank name and the user can enter the name after the Student object has been created.
I tried the following ...
Remove the default constructor from Student. This works but it means I have to use a different constructor and pass in string.Empty for the student name. The main issue with this is that we have some other generic code for creating new objects that requires our classes to have default constructors. It's also not a solution for all of our classes.
Change
IEnumerable<IStudent>toList<IStudent>. This works and it's what I started doing in our code, but it then forces the use of List<> instead of the genericIEnumerable<>. It's just less flexible.Create
Func<string, IEnumerable<IStudent>, ISchool> schoolFactoryand useschoolFactory.Invoke("Test", Enumerable.Empty<IStudent>). This also works. It's more code, but I guess it's more explicit.
Is there a generic way I can stop Autofac from automatically filling an IEnumerable?