【问题标题】:how to scan another library with structure map如何使用结构图扫描另一个库
【发布时间】:2015-08-06 22:25:41
【问题描述】:

我有一个名为 ServiceLayer 的类库,其中包含以下代码:

IProductService.cs

public interface IProductService
{
    void AddNewProduct(Product product);
    IList<Product> GetAllProducts();
}

ProductService.cs

public class ProductService : IProductService
{
    readonly IDbSet<Product> _products;

    public ProductService(IUnitOfWork uow)
    {
        _products = uow.Set<Product>();
    }

    public void AddNewProduct(Product product)
    {
        _products.Add(product);
    }

    public IList<Product> GetAllProducts()
    {
        return _products.Include(x => x.Category).ToList();
    }
}

我安装了 Structuremap.MVC5,所以在DefaultRegistry 文件中我有以下代码:

DefaultRegistry.cs

 public DefaultRegistry()
    {
        Scan(
            scan =>
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.With(new ControllerConvention());
            });

        For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use(() => new ApplicationDbContext());
    }

但是结构图不起作用并给了我这个异常:

“StructureMap.StructureMapConfigurationException”类型的异常 发生在 StructureMap.dll 中,但未在用户代码中处理

附加信息:没有注册默认实例,无法自动确定类型“MEF.ServiceLayer.IProductService”

所以我的问题是,结构映射如何扫描除主项目之外的另一个类库?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-5 structuremap


    【解决方案1】:

    您应该尝试添加包含 IProductService 的程序集。例如

    Scan(
       scan =>
          {
             scan.TheCallingAssembly();
             scan.WithDefaultConventions();
             // Add the assembly that contains a certain type
             scan.AssemblyContainingType<IProductService>();
             scan.With(new ControllerConvention());
          }
        );
    

    如果上述方法不起作用,那将是ProductServce 中缺少默认构造函数。尝试添加以下内容:

    public class ProductService : IProductService
    {
       readonly IDbSet<Product> _products;
       [DefaultConstructor]
       public AccountController()
       {
    
       }
    
       ...
    }     
    

    【讨论】:

    • 谢谢,现在可以使用了。但是我没有添加AssemblyContainingType,而是添加了Assembly,因为我将来可能会删除IProductService
    【解决方案2】:

    如果你引用了包含IProductService的项目,你可以使用Assembly方法并传递项目名称:

    Scan(scan =>
         {
                    // YourProject.Service: The project that contains IProductService
                    scan.Assembly("YourProject.Service");
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
         });
    

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2016-08-17
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多