Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

dependency injection - Passing constructor arguments when using StructureMap

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...