48

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.

Mosh
  • 5,944
  • 4
  • 39
  • 44

3 Answers3

63

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.

Jaxidian
  • 13,081
  • 8
  • 83
  • 125
Michael Hedgpeth
  • 7,732
  • 10
  • 47
  • 66
  • 5
    I'm guessing this is the place were you configure StructureMap. How do You pass the `someValueAtRunTime` there? – user1713059 Nov 06 '16 at 21:49
36

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.

Mosh
  • 5,944
  • 4
  • 39
  • 44
  • 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 09 '11 at 11:59
  • 5
    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 '13 at 15:31
  • 1
    @Mosh thank you for the answer, how ever can you please tell me how are you passing someValueAtRuneTime? an example of it please. – wandos Mar 30 '17 at 06:43
0

If you are running structuremap 2.6.x you will have to do the following:

For<IProductProvider>().Use<ProductProvider>().WithProperty("name").EqualTo(someValueAtRunTime);

Ensure the property name matches the constructor argument.

If your parameter is coming from the app settings use the following line:

.WithProperty("").EqualToAppSetting("")
JWallace
  • 487
  • 4
  • 7