结构图 - 具有依赖性的设置依赖性

时间:2017-03-31 12:51:36

标签: c# .net asp.net-web-api2 nullreferenceexception structuremap

我正在使用结构图作为我的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时,我得到null引用异常的运行时错误:

{
  "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()"
}

这就是我对结构图

所做的
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 个答案:

答案 0 :(得分:1)

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

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