Martin
Martin

Reputation: 427

Construct dependency chain with arguments at the root

I the following dependency chain:

Handler() [depends on]--> Repository(string connectionString)

So, I have an IHandler which depends on the IRepository which in turn requires a connection string. The connection string is dynamic and is passed during runtime (so it can't be read from a config file etc.)

Imagine the system creates the handler with the following code:

var handler = ObjectFactory.GetInstance<IHandler>();

This fails because the Repository dependency (the connectionString) can't be satisfied. My next idea was to use StructureMap's ExplicitArguments to supply arguments at the start of the dependency chain construction, i.e:

var arguments = new ExplicitArguments();
arguments.SetArg("connectionString", "SOME CONNECTION STRING");

var handler = ObjectFactory.GetInstance<IHandler>(arguments);

This fails because StructureMap now expects to find a connectionString dependency in Handler (and if it has one, doesn't pass those arguments down to the Repository constructor anyway).

The question is: Is there a way to construct this chain by supplying arguments at the top of it and letting StructureMap figure out that the repository needs the connectionString argument?

Upvotes: 3

Views: 563

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233437

container.Configure(r => r
    .ForConcreteType<Repository>()
    .Configure.Ctor<string>().Is("some connection string"));

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

If you have influence on the Repository I suggest you change the constructor to require a IConnectionStringProvider and register an instance of a class implementing that interface with your object factory.

Upvotes: 1

Related Questions