I'm looking to use Unity to resolve types at runtime based on specific data received. My code (similar to that shown below) currently registers the types in a bootstrapper class at start-up and then within the main flow a decision is made on what type is required.
What I'm looking to do is replace the code lines that use the 'new' keyword with a resolver, however as this code is outwith my bootstrapper I'm not sure how this can be done...I'm new to Unity so please go easy.
// In Bootstrapper class
resolver.RegisterType<IDataType1, DataType1>();
resolver.RegisterType<IDataType2, DataType2>();
resolver.RegisterType<IDataType3, DataType3>();
// Main flow...outwith bootstrapper
switch (dataRecordType)
{
case DataRecordType.dataType1:
DataType1 dt1 = new DataType1();
dt1.ProcessData();
break;
case DataRecordType.dataType2:
DataType2 dt2 = new DataType2();
dt2.ProcessData();
break;
case DataRecordType.dataType3:
DataType3 dt3 = new DataType3();
dt3.ProcessData();
break;
default:
break;
}
You are missing a few abstractions here. You're missing an general abstraction over your data types and an abstraction for creating implementations of those data types:
What you can see is that the code for creating implementations is moved to the factory. Now the remaining application code can be comes something like this:
The
IDataType1
,IDataType2
andIDataType3
are now only used in the bootstrapper and have become redundant (or at least, redundant with the code you presented), so you could even remove them all together and change the bootstrap logic to the following: