views:

229

answers:

1

Hi, is there a way using the Unity framework to pass an integer as an argument into the constructor or a resolved object?

Pseudo code..

IService svc = Container.Resolve<ConcreteService>()

in this case Concrete service will be something like this...

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

Also I need to do this in xml configuration as opposed to doing it in code.

Thanks in advance.

+2  A: 

Hope I understood you right

   public class ConcreteService {

        public int Val { get; set; }

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

Now let's configure 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

Equvivalent 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

It's much the same but without redundant typeConfig node

<type type="ConcreteService"  name="for42">
        <constructor>
              <param name="val" parameterType="int">
                <value value="42"/>
              </param>
            </constructor>           
        </type>
er-v