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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm guessing this is the place were you configure StructureMap. How do You pass the someValueAtRunTime there?
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.

3 Comments

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.
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?
@Mosh thank you for the answer, how ever can you please tell me how are you passing someValueAtRuneTime? an example of it please.
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("")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.