I have two example classes
class ClassToResolve
{
private List<CollectionItem> _coll;
public ClassToResolve(List<CollectionItem> coll)
{
_coll = coll;
}
}
class CollectionItem
{
//...
}
and I need to resolve ClassToResolve
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
new CollectionItem(),
new CollectionItem(),
new CollectionItem()
}
);
Now I resolve it in a way
var classToResolve = new ClassToResolve(
new List<CollectionItem>()
{
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>(),
unity.Resolve<CollectionItem>()
}
);
Is there a way to resolve ClassToResolve with Unity using dynamic registration?
Traditional factory-based dependency injection This is mature, well-tested and it works under Unity. We have used it to structure significant parts of our many Unity applications. This kind of factory supports code isolation for unit-testing.
You declare array variables much like any other variable, set a DataType, add the square brackets “[ ]” indicating this is an array, and finish it with the variable name. And just like any other variable, you can assign a value to it upon declaration, or re-assign a value later.
Basic Syntax To initialize a dictionary with key-value pairs: Use a pair of curly brackets at the end of the declaration. Add each element within its pair of curly brackets, with the key and the value separated by a comma. Separate elements with a comma, except the last element where the comma is optional.
Unity will understand that T[]
(array) dependencies are a list of things (but not IEnumerable<T>
, nor List<T>
). When you change the constructor of ClassToResolve
to take an CollectionItem[]
instead of a List<CollectionItem>
you can configure your CollectionItem
types as follows:
container.RegisterType<CollectionItem, CollectionItemA>("a");
container.RegisterType<CollectionItem, CollectionItemB>("b");
container.RegisterType<CollectionItem, CollectionItemC>("c");
container.RegisterType<CollectionItem, CollectionItemD>("d");
The trick here is to name all the registrations. A default (nameless) registration will never be part of a sequence dependency in Unity.
Now you can resolve ClassToResolve
without the need to register it:
container.Resolve<ClassToResolve>();
If you rather inject List<CollectionItem>
you can add the following registration:
container.RegisterType<IList<CollectionItem>, CollectionItem[]>();
And for IEnumerable<CollectionItem>
you can add the following line:
container
.RegisterType<IEnumerable<CollectionItem>, CollectionItem[]>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With