Unity Framework - passing integers and strings to allowed objects

Is there a way to use the Unity framework to pass an integer as an argument to a constructor or resolved object?

Pseudocode ..

IService svc = Container.Resolve<ConcreteService>()

in this case, the concrete service will be something like this ...

public class ConcreteService
{
    public ConcreteService(int val)
    {
    }
}

Also I need to do this in the xml configuration, and not do it in the code.

Thanks in advance.

+3
source share
1 answer

I hope I understood you correctly.

   public class ConcreteService {

        public int Val { get; set; }

        public ConcreteService(int val) {
            Val = val;
        }
    }

Now set up unity.

        var container = new UnityContainer();

        container.RegisterType<ConcreteService>();
        container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>(new InjectionConstructor(1));

        container.RegisterType<ConcreteService>("for42");
        container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for42",
                                                                                      new InjectionConstructor(42));
        container.RegisterType<ConcreteService>("for31");
        container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for31",
                                                                                      new InjectionConstructor(31));

        Debug.WriteLine(container.Resolve<ConcreteService>().Val); //1
        Debug.WriteLine(container.Resolve<ConcreteService>("for42").Val); //42
        Debug.WriteLine(container.Resolve<ConcreteService>("for31").Val); //31

The equivalent configuration for "for42" is

Unity 1.4

<type type="ConcreteService"  name="for42">
          <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
                                     Microsoft.Practices.Unity.Configuration">
            <constructor>
              <param name="val" parameterType="int">
                <value value="42"/>
              </param>
            </constructor>           
          </typeConfig>
        </type>

Unity 2.0

This is the same, but without the redundant type Config node

<type type="ConcreteService"  name="for42">
        <constructor>
              <param name="val" parameterType="int">
                <value value="42"/>
              </param>
            </constructor>           
        </type>
+5
source

Source: https://habr.com/ru/post/1742956/


All Articles