Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using StructureMap for my DI. Imagine I have a class that takes 1 argument like:

public class ProductProvider : IProductProvider
{
     public ProductProvider(string connectionString)
     { 
         ....
     }
}

I need to specify the "connectionString at run-time when I get an instance of IProductProvider.

I have configured StructureMap as follows:

ForRequestedType<IProductProvider>.TheDefault.Is.OfConcreteType<ProductProvider>().  
WithCtorArgument("connectionString");

However, I don't want to call EqualTo("something...") method here as I need some facility to dynamically specify this value at run-time.

My question is: how can I get an instance of IProductProvider by using ObjectFactory?

Currently, I have something like:

ObjectFactory.GetInstance<IProductProvider>();  

But as you know, this doesn't work...

Any advice would be greatly appreciated.

share|improve this question

2 Answers

I suggest declaring that with the StructureMap configuration. Using the slightly newer StructureMap code:

For<IProductProvider>().Use<ProductProvider>
  .Ctor<string>("connectionString").Is(someValueAtRunTime);

This way you don't burden your client code from having to know the value and can keep your IoC configuration separate from your main code.

share|improve this answer
up vote 21 down vote accepted

I found the answer myself! Here is the solution:

ObjectFactory.With("connectionString").EqualTo(someValueAtRunTime).GetInstance<IProductProvider>();

Hope this helps others who have come across the same issue.

share|improve this answer
1  
Make sure that someValueAtRuntime is a simple value, not any kind of Func or Lambda (if you can do that) for retrieving it, otherwise that function will run every time the dependency is resolved. I used this trick to inject a connection string, just as you're doing. As long as you get the string into a local variable before setting up ObjectFactory, you should be fine. – Mel Aug 9 '11 at 11:59
Yo. What if I have several arguments, arg1, 2, 3 etc. And I want to pass in every argument as is but keep one of the args as null. How to do this? – J0NNY ZER0 Feb 21 at 15:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.