Passing constructor arguments when using StructureMap

前端 未结 3 468
暗喜
暗喜 2020-12-03 09:24

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

public class ProductProvider : IProductProvider
{
     public ProductPr         


        
相关标签:
3条回答
  • 2020-12-03 10:09

    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.

    0 讨论(0)
  • 2020-12-03 10:13

    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.

    0 讨论(0)
  • 2020-12-03 10:17

    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("")
    
    0 讨论(0)
提交回复
热议问题