我有一个名为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());
}
但结构图并不起作用,并且给了我这个例外:
类型&#39; StructureMap.StructureMapConfigurationException&#39;的例外。 发生在StructureMap.dll中但未在用户代码中处理
其他信息:没有注册默认实例,无法自动确定类型&#39; MEF.ServiceLayer.IProductService&#39;
所以我的问题是,结构图如何扫描除主项目之外的另一个类库?
答案 0 :(得分:0)
您应该尝试添加包含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()
{
}
...
}
答案 1 :(得分:0)
如果您引用了包含IProductService
的项目,则可以使用Assembly方法并传递项目名称:
Scan(scan =>
{
// YourProject.Service: The project that contains IProductService
scan.Assembly("YourProject.Service");
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});