views:

472

answers:

2

I have the concrete types for interfaces configured at startup, but I want to create instances of the concrete type at runtime with setting properties or setting different values in the constructor. All the creating of instances I see have the knowledge of what the concrete type is, at runtime I dont know the concrete type. Is there a way to create a concrete instance of an interface/class without knowing the concrete type? This is what I have seen:

 [Test]

        public void DeepInstanceTest_with_SmartInstance()

        {

            assertThingMatches(registry =>

            {

                registry.ForRequestedType<Thing>().TheDefault.Is.OfConcreteType<Thing>()

                    .WithCtorArg("name").EqualTo("Jeremy")

                    .WithCtorArg("count").EqualTo(4)

                    .WithCtorArg("average").EqualTo(.333);

            });

        }

OR:

var container = new  Container(x =>

            {

                x.ForConcreteType<SimplePropertyTarget>().Configure

                    .SetProperty(target =>

                    {

                        target.Name = "Max";

                        target.Age = 4;

                    });

            });

I want to do something similar...but dont know the concrete type....only the abstract class or interface (would have properties in this case). The concrete type is configured though.

A: 

You need some kind of factory pattern to create the concrete instances. The instant of creation necessarily needs to know what the concrete implementation is.

JaredReisinger
you dont need a factory pattern because StructureMap takes care of that for you. I did find the answer though...thanks.
CSharpAtl
+2  A: 

Found the answer with direction from Jeremy Miller (author of StructureMap). Here is where he pointed me to:

http://structuremap.sourceforge.net/RetrievingServices.htm#section5

here is an example of what I used:

IDatabaseRepository repo =
                ObjectFactory.With("server").EqualTo("servername").
                With("database").EqualTo("dbName").
                With("user").EqualTo("userName").
                With("password").EqualTo("password").
                GetInstance<IDatabaseRepository>();
CSharpAtl