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>();