1

我使用结构图作为我的IOC与Web API,我有一个注入的依赖项在我的控制器中,它的具体类型也有一个依赖关系。结构图 - 具有依赖关系的安装依赖关系

控制器

[RoutePrefix("api/products")] 
public class ProductsController : BaseApiController 
{ 

    //private readonly ProductRepository _manageProducts; 
    private readonly IProductFactory _productFactory; 
    private readonly IGenericRepository _genericRepository; 

    public ProductsController(IProductFactory productFactory, IGenericRepository genericRepository) 
    { 
     _productFactory = productFactory; 
     _genericRepository = genericRepository; 
     //_manageProducts = new ProductRepository(); 
    } 

    [Authorize] 
    [Route("addProduct")] 
    public IHttpActionResult AddNewProduct(ProductViewModels.AddProductViewModel product) 
    { 
     if (User.IsInRole("Admin")) 
     { 

      _productFactory.CreateProduct(product); 
      return Ok("Product Successfully Added"); 
     } 
     return BadRequest("Your must have Administrator rights to perform the operation."); 
    } 
} 

public class ProductFactory : IProductFactory 
{ 
    private readonly IGenericRepository _genericRepository; 

    public ProductFactory(IGenericRepository genericRepository) 
    { 
     _genericRepository = genericRepository; 
    } 


    /// <summary> 
    /// Creates the product. 
    /// </summary> 
    /// <returns>The product.</returns> 
    /// <param name="viewModel">New product.</param> 
    public Product CreateProduct(ProductViewModels.AddProductViewModel viewModel) 
    { 
     var productToBeAdded = new Product 
     { 
      Title = viewModel.Title, 
      ISBN = viewModel.ISBN, 
     }; 
     return productToBeAdded; 
    } 
} 

当我打电话产品控制器addproducts我得到空引用异常此运行时错误:

{ 
    "Message": "An error has occurred.", 
    "ExceptionMessage": "Object reference not set to an instance of an object.", 
    "ExceptionType": "System.NullReferenceException", 
    "StackTrace": " at ICEBookshop.API.Factories.ProductFactory.CreateProduct(AddProductViewModel viewModel) in C:\\Users\\GOWDY_N\\Source\\Repos\\ICEBookshop.API\\ICEBookshop.API\\P00603ClientApi\\Factories\\ProductFactory.cs:line 29\r\n at ICEBookshop.API.Controllers.ProductsController.AddNewProduct(AddProductViewModel product) in C:\\Users\\GOWDY_N\\Source\\Repos\\ICEBookshop.API\\ICEBookshop.API\\P00603ClientApi\\Controllers\\ProductsController.cs:line 95\r\n at lambda_method(Closure , Object , Object[])\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()" 
} 

这是我和structuremap

public class DefaultRegistry : Registry 
{ 
    #region Constructors and Destructors 

    public DefaultRegistry() 
    { 
     Scan(
      scan => 
      { 
       scan.TheCallingAssembly(); 
       scan.WithDefaultConventions(); 
      }); 
     For<IGenericRepository>().Use<GenericRepository<ApplicationDbContext>>(); 
     For<IProductFactory>() 
      .Use<ProductFactory>() 
      .Ctor<IGenericRepository>() 
      .Is<GenericRepository<ApplicationDbContext>>().Named("DefaultInstanceKey"); 


     #endregion 
    } 
} 

做我是这么认为的它知道如何解决我的工厂,这将解决这个问题:

For<IProductFactory>() 
        .Use<ProductFactory>() 
        .Ctor<IGenericRepository>() 
        .Is<GenericRepository<ApplicationDbContext>>().Named("DefaultInstanceKey"); 

但它不工作也没有。有谁知道如何解决这一问题?

回答

1

只需注册两个接口及其实现。该框架将在解析目标时解决依赖关系。

For<IGenericRepository>().Use<GenericRepository<ApplicationDbContext>>(); 
For<IProductFactory>().Use<ProductFactory>();