CSharpAtl
CSharpAtl

Reputation: 7512

StructureMap creating instance

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 don't 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 don't know the concrete type....only the abstract class or interface (would have properties in this case). The concrete type is configured though.

Upvotes: 2

Views: 3482

Answers (2)

CSharpAtl
CSharpAtl

Reputation: 7512

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>();

Upvotes: 2

JaredReisinger
JaredReisinger

Reputation: 7173

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.

Upvotes: 0

Related Questions