【问题标题】:Setting up OrmLite with StructureMap使用 StructureMap 设置 OrmLite
【发布时间】:2016-03-27 10:44:53
【问题描述】:

我想用 StructureMap 创建 OrmLite 的基本 IoC,但我做错了。

在 OrmLite 的网站上,他们给出了一个如何注入它的简单示例:

container.Register<IDbConnectionFactory>(c => 
    OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)); //InMemory Sqlite DB

所以我想在我新创建的带有 StructureMap 的 WebAPI2 应用程序中使用它。

我已经安装了 StructureMap.WebAPI2 nuget 并且我有以下配置:

 container.Configure(x => {
        x.For<IAuthenticationService>().Use<AuthenticationService>();

        x.For<IDbConnectionFactory>()
                    .Use<OrmLiteConnectionFactory>().Ctor<string>("connectionString").Is("Server=(localdb)\v11.0;Integrated Security=true;")
                    .Ctor<IOrmLiteDialectProvider>("dialectProvider").Is(SqlServerOrmLiteDialectProvider.Instance);
  });

在这种情况下,IAuthenticationServer 被正常实例化。但是当我尝试访问 DbConnection 时,它没有被注入,它是空的

    public IDbConnectionFactory DbFactory { get; set; } //injected by IOC

    IDbConnection db;
    IDbConnection Db
    {
        get
        {
            return db ?? (db = DbFactory.Open());
        }
    }

这就是我试图访问数据库的方式。在 getter DbFactory 中为空。我该如何解决?

【问题讨论】:

    标签: c# asp.net structuremap ormlite-servicestack


    【解决方案1】:

    StructureMap 不会自动进行 setter 注入(通过有意识的设计),您必须选择加入。要么更改你的类,以便通过构造函数注入 IDbConnection(首选),要么检查一下以了解如何使用带有 StructureMap 的 setter 注入:http://structuremap.github.io/setter-injection/

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多