Dependency injection not working in web api call

笑着哭i 提交于 2020-01-25 21:42:12

问题


Hi I am trying to build angular 2 web application using WebAPI, Entityframework that is loosely coupled using dependency injection. I am using unity for dependency injection. I have created multiple projects in one solution to address the separation concerns.

I have configured the dependency in unity.config however when i execute the webapi application and type the following url http://localhost:8702/api/allcustomers , I get message saying the customer controller doesn't have parameter-less constructor. I have set my break points in unity.config which never get hit

I would like to to understand if my implementation is correct as well

Below is the structure of my solution

CustomerOrder.Business.Objects CustomerOrder.Data.Objects (references the business object) CustomerOrder.Service.Api (references business object and service implementation) CustomerOrder.Service.Implementation (references business objects and data objects) CustomerOrder.Web (Yet to implement)

Below is the code

CustomerOrder.Business.Objects

 public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }

        public int? Zip { get; set; }

    }

CustomerOrder.Data.Objects

    public class CustomerDao : ICustomerDao
        {

            IEnumerable<CustomerOrder.BusinessObjects.Customer> ICustomerDao.GetAllCustomers()
            {
                using (var customerOrderContext = new Entities())
                {
                    return (from customer in customerOrderContext.Customers

                            select new CustomerOrder.BusinessObjects.Customer
                            {
                                Id = customer.Id,
                                FirstName = customer.FirstName,
                                LastName = customer.LastName,
                                Address = customer.Address,
                                City = customer.City,
                                Email = customer.Email,
                                Gender = customer.Gender,
                                State = customer.State,
                                Zip = customer.Zip
                            }).ToList();
                }
            }
      }


    public interface ICustomerDao
        {

            /// <summary>
            /// Get All Customers
            /// </summary>
            /// <returns></returns>
            IEnumerable<Customer> GetAllCustomers();

        }

        public interface IDaoFactory
        {
            ICustomerDao CustomerDao { get; }

        }
    }

  public class DaoFactory : IDaoFactory
    {
        public DaoFactory(ICustomerDao CustomerDao, IProductDao ProductDao, IOrderDao OrderDao)
        {
            this.CustomerDao = CustomerDao;
        }

        public ICustomerDao CustomerDao { set; get; }





    }

CustomerOrder.Service.Api

Unity.Config 

    public static void RegisterComponents()
            {
                var container = new UnityContainer();

                // register all your components with the container here
                // it is NOT necessary to register your controllers

                // e.g. container.RegisterType<ITestService, TestService>();

                container.RegisterType<ICustomerProvider, CustomerProvider>();
                container.RegisterType<IOrderProvider, OrderProvider>();
                container.RegisterType<IProductProvider, ProductProvider>();

                GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            }

CustomerController.cs

    public class CustomerController : ApiController
        {
            private ICustomerProvider customerProvider;


            public CustomerController(ICustomerProvider customerProvider)
            {
                this.customerProvider = customerProvider;
            }

            [Route("api/allcustomers")]
            public IEnumerable<Customer> GetAllCustomers()
            {
                return customerProvider.GetAllCustomers();
            }

CustomerOrder.Service.Implementation

public interface ICustomerProvider
{

    IEnumerable<BusinessObjects.Customer> GetAllCustomers();

}

 public class CustomerProvider : ICustomerProvider
    {

        private readonly IDaoFactory dataAccess;

        public CustomerProvider(IDaoFactory dalFactory)
        {
            this.dataAccess = dalFactory;
        }

        public IEnumerable<BusinessObjects.Customer> GetAllCustomers()
        {
            IList<BusinessObjects.Customer> customerCollection = new List<BusinessObjects.Customer>();
            dataAccess.CustomerDao.GetAllCustomers();
            return customerCollection;
        }
}

Context Class

namespace CustomerOrderData.EF
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class Entities : DbContext
    {
        public Entities()
            : base("name=Entities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
         //   throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Customer> Customers { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<Order> Orders { get; set; }
        public virtual DbSet<Product> Products { get; set; }
    }
}

回答1:


In CustomerProvider, the IDaoFactory is probably not getting resolved because it's not registered. Add this to the Unity.Config:

container.RegisterType<IDaoFactory , DaoFactory >();



回答2:


Please try including a parameterless constructor into the customer controller.

public CustomerController() {}



回答3:


You should register not only IDaoFactory and his constructor dependencies

container.RegisterType<IDaoFactory, DaoFactory>();
container.RegisterType<ICustomerDao, CustomerDao>();
container.RegisterType<IOrderDao, OrderDao>();
container.RegisterType<IProductDao, ProductDao>();


来源:https://stackoverflow.com/questions/40358875/dependency-injection-not-working-in-web-api-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!