Search code examples
dryioc

DryIoc, how to set the properties to the base class?


I've written the following POC, but I have to admit I'm very confused on how to achieve this.

public class Parent
{
    public string Str;

    public Parent()
    {
    }
}

public class Child : Parent
{

}

public class Program
{
    static void Main(string[] args)
    {
        var container = new Container();
        var prop = typeof (Parent).GetMember(nameof(Parent.Str)).First();
        var x = new [] { PropertyOrFieldServiceInfo.Of(prop) };
        container.Register<Parent, Parent>(made: Made.Of(propertiesAndFields: (r) => x));
        // Set "X" somewhere??    
        container.Register<Child, Child>();

        var parent = container.Resolve<Parent>();
        var child = container.Resolve<Parent>();
    }
}

my goal, is child and (less importantly) parent both have their Str property set to "X".

I need to know because I would like to convert from Spring.Net to DryIoc where it's like the following.

<object id="parentManager_transport" abstract="true">
  <property name="EntityManager" ref="entityManager_transport"/>
</object>

<object id="carManager" type="xxx" parent="parentManager_transport"/>
<object id="carMakerManager" type="yyy" parent="parentManager_transport"/>
<object id="carFuelManager" type="zzz" parent="parentManager_transport"/>

Solution

  • There is a sugar PropertiesAndFields static class with methods to specify what to inject based on name, type or condition:

    container.Register<Parent>(
        made: PropertiesAndFields.Of.Name("Str", serviceKey: "someId"));
    

    To set property just register it. To distinguish it from possibly multiple registered strings specify service key:

    container.RegisterInstance("my string", serviceKey: "someId");