Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 521
Martin Avatar asked Mar 06 '26 05:03

Martin


2 Answers

container.Configure(r => r
    .ForConcreteType<Repository>()
    .Configure.Ctor<string>().Is("some connection string"));
like image 178
Mark Seemann Avatar answered Mar 08 '26 19:03

Mark Seemann


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.

like image 29
Daniel Hilgarth Avatar answered Mar 08 '26 19:03

Daniel Hilgarth