【问题标题】:Injecting a connection string with StructureMap not working使用 StructureMap 注入连接字符串不起作用
【发布时间】:2011-11-15 22:33:34
【问题描述】:

我对结构图还是很陌生,所以我不明白为什么这不起作用。我正在向存储库注入“连接字符串”,并且不断从结构映射中收到以下错误:

结构图异常代码:205 InstanceKey“a04b4f71-4171-4e9f-b98d-170fc9ee005f”缺少请求的实例属性“purchaseOrdersFilePath”

附带说明,连接字符串用引号引起来,因为我也在使用 linq to xml,所以“连接字符串”实际上是文件的路径。我添加这个以防万一它可能与问题有关。

我的代码如下:

public class PurchaseOrderRepository : IPurchaseOrderRepository
{
    private readonly string PurchaseOrdersFilePath;

    public PurchaseOrderRepository(string purchaseOrdersFilePath)
    {
        if (string.IsNullOrWhiteSpace(purchaseOrdersFilePath)) throw new ArgumentNullException("purchaseOrdersFilePath");

        PurchaseOrdersFilePath = purchaseOrdersFilePath;
    }
 }

在我的 Global.asax 文件中,我有以下配置语句:

private void RegisterControllerFactory()
{
    var ioc = new Container();

    var controllerFactory = new IocControllerFactory(ioc);
    ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    ioc.Configure(r => r.Scan(x =>
    {
        x.AssemblyContainingType<HomeController>();
        x.AddAllTypesOf<IController>();
        x.Include(t => typeof(IController).IsAssignableFrom(t));
    }));

    ioc.Configure(r => r
        .ForConcreteType<PurchaseOrderRepository>()
        .Configure.Ctor<string>().Is(@"C:\Users\sromero\Documents\Visual Studio 2010\Projects\DIDemo\SupportFiles\POS.xml"));
}

我做错了什么?

感谢您的帮助。

【问题讨论】:

    标签: c# dependency-injection structuremap


    【解决方案1】:

    原来我配置了两次相同的组件(我没有反映问题中的示例代码),所以我正在做的是:

    ioc.Configure(r => r
                    .For<IPurchaseOrderRepository>()
                    .Use<PurchaseOrderRepository>());
    
        ioc.Configure(r => r
                .ForConcreteType<PurchaseOrderRepository>()
                .Configure.Ctor<string>().Is(@"C:\Users\sromero\Documents\Visual Studio 2010\Projects\DIDemo\SupportFiles\POS.xml"));
    

    什么时候我应该做的是:

    ioc.Configure(r => r
                    .For<IPurchaseOrderRepository>()
                    .Use<PurchaseOrderRepository>()
                    .Ctor<string>().Is(@"C:\Users\sromero\Documents\Visual Studio 2010\Projects\DIDemo\SupportFiles\POS.xml"));
    

    【讨论】:

      【解决方案2】:

      试试:

      .Ctor<string>("purchaseOrdersFilePath").Is(@"C:\Users\sromero\Documents\Visual Studio 2010\Projects\DIDemo\SupportFiles\POS.xml"));
      

      【讨论】:

      • 谢谢,但是没有用。我仍然得到完全相同的错误。
      猜你喜欢
      • 2021-01-26
      • 2018-09-03
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2013-11-04
      • 1970-01-01
      相关资源
      最近更新 更多