Search code examples
iosdependency-injectiontyphoon

Initializing object with non property methods in Typhoon


I'm new to DI and Typhoon in particular. I'm wondering if its possible to initialize an object with methods other than init methods and properties. I have a class called ObjectMapper, an ObjectMapper can have N number of ObjectMaps. Before using typhoon, I would create the maps like so:

ObjectMap *map1 = [ObjectMap new]; [map1 mapProperty:@"prop1" toName:@"name1"]; [map1 mapProperty:@"prop2" toName:@"name2"]; ObjectMap *map2 = [ObjectMap new]; [map2 mapProperty:@"prop3" toName:@"name3"]; mapper.maps = @[map1, map2];

The maps and the mapper object never change throughout the lifetime of the application. I would like to create the ObjectMapper and the ObjectMaps in Typhoon. Update: It seems that a TyphoonFactoryProvider might help but I can't figure out how to place object created by the factory into the 'maps' array.


Solution

  • TyphoonFactoryProvider is not going to help you here - this (advanced) class just provides a clean way to obtain an instance where some of the initializer-arguments or properties aren't known until run-time. . normally here you'd either:

    • Obtain the instance and then configure it with the runtime known args in two separate steps
    • Create a custom factory

    TyphoonFactoryProvider just writes the custom factory code for you, as well as handles some memory management details. (lazy dependencies). Its useful for eg: transitioning from one view controller to another.

    If I understand you, what you're trying to do is not directly possible with Typhoon. However, you could always inject an object instance (configuration info) along with an afterPropertyInjection callback to finish off. Example:

    -(id) mappedComponent
    {
        return [TyphoonDefinition withClass:[MyType class] properties:^(TyphoonDefinition* definition)
        {
            // Any object. This time an NSDictionary using Objc literals shorthand 
            [definition injectProperty:@selector(mappings) withObjectInstance:@{
                @"prop1" : @"name1", 
                @"prop2" : @"name2", 
                @"prop3" : @"name3" 
             }];   
             //This can be a category method if you don't "own" the class in question. The method puts the object in the required state, using the config data provided. 
             definition.afterPropertyInject = @selector(myConfigMethod)];  
          }];
     }