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", "SOM开发者_如何学JAVAE 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?
container.Configure(r => r
.ForConcreteType<Repository>()
.Configure.Ctor<string>().Is("some connection string"));
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.
精彩评论