views:

82

answers:

1

Hi.

I am using the Unity fluent API to inject property values on an object. My program obtains the value of the properties from an external configuration source, an xml file.

The problem I am facing is that the property I am attempting to set is of type Int32, but the value, having been read from an xml file, is initially cast as a string. What do I need to do to make Unity do the necessary type conversion? If I configure the container in a Unity config file, it works, however I'm not sure what further steps are required when doing this in code.

Here is my code:

        using (IUnityContainer taskContainer = new UnityContainer())
        {
            taskContainer.RegisterType(typeof(ITask), jobType);

            // Configure properties
            foreach (PropInfo prop in jobConfig.Props)
            {
                // The next line raises an exception when setting an Int32 property
                taskContainer.RegisterType(jobType, new InjectionProperty(prop.Name, prop.Value));
            }

            ITask myTask = taskContainer.Resolve<ITask>();
        }

Glossary: * prop.Value is of type Object. * the property which is being injected is of type Int32. * jobType is of type Type and has been assigned previously. * PropInfo is a bespoke helper class for accessing config info. * jobInfo is an instance of a similar helper class.

The code works well for injecting properties values to string properties but when I hit the Int32 property I get the exception: "The property RetryCount on type DynamicTask is of type Int32, and cannot be injected with a value of type String". [Obviously the name of the property is RetryCount and it is on an object named DynamicTask].

I am guessing that I need to do some preceding steps to register the type of the property being injected, but I cannot work out the syntax, there are some examples in the Unity documentation but I'm not sure if they apply to my situation.

I would be very grateful if someone could tell me what preceding steps I need to take.

Many thanks in advance.

A: 

Unity's API doesn't do the kind of type conversion you're asking for. We use the .NET TypeConverter infrastructure to handle the conversion from the XML side, but it's typically not needed in the API so we don't have any special handling for it.

The solution you've come up with is as good as any other.

Chris Tavares