How can I create an object directly

Mar 1, 2009 at 12:27 PM
Is it possibe to get instance of a type configured in webconfig? I mean I wolud like to do this:

A objectA = MyContainer.resolve<A>()  where A is not interface or base class, just a class.

if it is possible then how can I write it in 'MyContainer' tag at webconfig.

Mar 2, 2009 at 8:02 AM
Yes, you could just register an instance in the <instances> section directly under a <container> element.

types here....
add name="emp" type="Sample.Employee, Sample" value="Jack" typeConverter="Sample.MyTypeConverter, Unity4.1" />

Note that I also specified a typeconverter.  This is necessary to convert the value you specified in the value attribute to the type you defined the type attribute.  In my case, my Employee class has a constructor which accepts a string.  My typeconverter looks like this:

public class MyTypeConverter : TypeConverter
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
return new Employee(value.ToString());




You can just then call the Resolve method of the container passing the name for the instance you specified in the config ("emp" in this case).

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.



Mar 4, 2009 at 1:46 AM
Actually, if all you're doing is to resolve a concrete type and your constructor isn't ambiguous, you can just do container.Resolve<Foo>() and it'll do the right thing, no configuration or instance registration required.

Mar 4, 2009 at 7:26 AM
In this case, how can I say it you are singleton?
Mar 4, 2009 at 6:44 PM
If you want it to be a singleton, then you do need some configuration.

You can specify lifetime without giving a type mapping:

<type type="Foo">
  <lifetime type="singleton"/>

would do the trick (assuming appropriate type aliases).

From the API:

container.RegisterType<Foo>(new ContainerControlledLifetimeManager());