【问题标题】:StructureMap select multiple constructor on GenericRepositoryStructureMap 在 GenericRepository 上选择多个构造函数
【发布时间】:2013-05-25 12:46:27
【问题描述】:

我正在使用来自 https://github.com/huyrua/efprs 的 GenericRepository 模式。我只想选择以 DbContext 作为参数的构造函数。我知道有重复的问题,但来自this 的解决方案没有解决。这是我的配置:

ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.AssemblyContainingType<Data.Entity.TokoContainer>();
        scan.WithDefaultConventions();
    });
    x.For<DbContext>().Use<Data.Entity.TokoContainer>();
    x.For<Infrastructure.Data.IRepository>()
     .Use<Infrastructure.Data.GenericRepository>()
     .Ctor<DbContext>().Is(c => c.GetInstance<DbContext>());
});

这会导致错误“StructureMap 异常代码:具体类型 Infrastructure.Data.GenericRepository 没有 System.Data.Entity.DbContext 类型的参数”。

使用时:

x.SelectConstructor<Infrastructure.Data.IRepository>(() => new Infrastructure.Data.GenericRepository((DbContext)null));
x.ForConcreteType<Infrastructure.Data.IRepository>()
 .Configure.Ctor<DbContext>().Is(c => c.GetInstance<DbContext>());

导致“StructureMap 配置失败:错误 104”。

从第一个代码中指定,像这样添加参数名称“context”:

x.For<Infrastructure.Data.IRepository>()
 .Use<Infrastructure.Data.GenericRepository>()
 .Ctor<DbContext>("context").Is(c => c.GetInstance<DbContext>());

导致错误“缺少 InstanceKey xxx 的请求的实例属性“connectionStringName””。我不知道现在该怎么办。

任何解决方案将不胜感激。

【问题讨论】:

  • “具体类型 Infrastructure.Data.GenericRepository 没有 System.Data.Entity.DbContext 类型的参数”。那是因为GenericRepository 依赖于ObjectContext。不是DbContext
  • 我使用的是同一个库并且有同样的异常。难怪

标签: c# entity-framework repository-pattern structuremap


【解决方案1】:

StructureMap 试图表达DbContext构造函数 带有字符串参数“connectionStringName”。正如您在附加的链接的测试场景中看到的那样:MyDbContext.cs

public class MyDbContext : DbContext
{
   ...    
   public MyDbContext(string connStringName) :
      base(connStringName)
   {
     ...

所以,我们需要做的是正确映射DbContext 的构造函数。例如:

x.For<DbContext>()
 .Use<Data.Entity.TokoContainer>()
 // example, taking the first conn string - adjust as needed
 .Ctor<string>().Is(ConfigurationManager.ConnectionStrings[0].ConnectionString);
;

现在,即使是 DbContext 也会正确设置

【讨论】:

  • 错误:StructureMap 异常代码:302。具体类型 Toko.Data.Entity.TokoContainer 没有 System.String 类型的参数
  • 如果 TokoContainer 是您的类,请更改其构造函数。无论如何,您都必须将 conn 字符串传递给基本 DBContext
猜你喜欢
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多