【问题标题】:How do I configure StructureMap to use a generic repository?如何配置 StructureMap 以使用通用存储库?
【发布时间】:2010-05-14 15:35:43
【问题描述】:

我有一个接口IGenericRepository<TEntity> where TEntity : IEntity 和一个实现GenericRepository<TEntity> where TEntity : Entity

我正在尝试使用 StructureMap 将特定的 IGenericRepository<Section> 注入到一个类中:

    ObjectFactory.Initialize(x =>
        {
            x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>));
        });

但是当我尝试使用 ObjectFactory.GetInstance&lt;IGenericRepository&lt;Section&gt;&gt;(); 我得到:

StructureMap 异常代码:202 没有为 PluginFamily System.Data.Common.DbConnection 定义默认实例

任何想法为什么会这样或我做错了什么?

提前致谢,

西蒙

【问题讨论】:

    标签: c# generics dependency-injection structuremap


    【解决方案1】:

    您在 GenericRepository 的构造函数中接收到一个 DbConnection,它是一个抽象类,并且没有配置 SM 以知道应该使用哪个特定类。

    即:

     ObjectFactory.Initialize(x =>
            {
                x.For(typeof(DbConnection)).Use(typeof(SqlConnection));
                x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>));
            });
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题:

      有一个通用存储库:

      public interface IRepository<TEntity> : IDisposable where TEntity : class
          { }
      

      和一个具体的实现:

      public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
          { }
      

      我想在运行时将其注入到控制器的构造函数中,其中 TEntity 将是与该控制器相关的模型:

      public FooBarController(IRepository<FOO_BAR_TYPE> repository)
              {
                  _repo = repository;
              }
      

      然后控制器将使用存储库“_repo”来更新模型:

      //
      // POST: /EmergencyServiceType/Create
      [HttpPost]
      public ActionResult Create(FOO_BAR_TYPE foobar)
      {
          if (ModelState.IsValid)
          {            
              // GetNextSequenceValue() deals with Oracle+EF issue with auto-increment IDs
              foobar.FOO_BAR_ID = _repo.GetNextSequenceValue(); 
              _repo.Add(foobar);
              _repo.SaveChanges();
              return RedirectToAction("Index");  
          }
      
          return View(foobar); // display the updated Model
      }
      

      simonjreid 为我解释了答案:必须将 ObjectContext 添加到 StructureMap 配置中(存储库的目的是包装由 EntityFramework 生成的上下文,我将其称为 MyContextWrapper。因此,因为存储库依赖于 MyContextWrapper,而后者又依赖于 MyContextWrapper取决于 ObjectContext):

      // This avoids 'No Default Instance for ...DbConnection' exception
      x.For<System.Data.Objects.ObjectContext>().Use<MyContextWrapper>();
      x.For<System.Web.Mvc.IController>().Use<Controllers.FooBarController>().Named("foobarcontroller"); // note that Named is required and is Case Sensitive
      

      但是,现在我得到了 StructureMap 运行时异常:

      结构图异常代码:205 缺少请求的实例属性“connectionString”

      在阅读了 Jeremy Miller A Gentle Quickstart 的帖子(位于底部)之后,我发现您可以定义要传递给已注册类型的构造函数的参数,即我需要将连接字符串传递给MyCustomContext 类(这里是我如何初始化 ObjectFactory 的完整列表:

      string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["MyContextWrapper"].ConnectionString;
      ObjectFactory.Initialize(x =>
                  {
                      x.Scan(scan =>
                              {
                                  // Make sure BUSINESS_DOMAIN assembly is scanned
                                  scan.AssemblyContainingType<BUSINESS_DOMAIN.MyContextWrapper>(); 
                                  scan.TheCallingAssembly();
                                  scan.WithDefaultConventions();
                              });
                      // 'connStr' below is a local variable defined above
                      x.For<System.Data.Objects.ObjectContext>()
                          .Use<MyContextWrapper>()
                          .Ctor<string>().Is(connStr);
                      x.For<System.Web.Mvc.IController>().Use<Controllers.FooBarController>().Named("foobarcontroller"); 
                  });
      

      然后砰!现在可以让我的 Controller 在运行时通过 StructureMap 实例化,并让它注入 IRepository 的一个实例......快乐的日子。

      【讨论】:

        【解决方案3】:

        GenericRepository&lt;&gt; 的构造函数是什么样的?

        它或其依赖项之一期待 SM 无法创建的 DbConnection

        【讨论】:

        • 谢谢你,我的通用存储库正在使用我没有通过 SM 添加的 ObjectContext
        • 这是一个答案还是另一个问题?如果这是一个问题,为什么将其标记为已接受的答案?
        猜你喜欢
        • 2011-02-24
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-17
        • 2013-08-26
        • 1970-01-01
        相关资源
        最近更新 更多