Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

How to inject repository by Unity ID

$
0
0

please discuss with code sample that how to inject repository dynamically in controller by Unity ID

now i am doing things like this way.

    public class CustomerController : ApiController
    {
        static readonly ICustomerRepository repository = new CustomerRepository();

        public IEnumerable<Customer> GetAllCustomers()
        {
            return repository.GetAll();
        }

        public Customer GetCustomer(string customerID)
        {
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return customer;
        }

        public IEnumerable<Customer> GetCustomersByCountry(string country)
        {
            return repository.GetAll().Where(
                c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
        }

        public HttpResponseMessage PostCustomer(Customer customer)
        {
            customer = repository.Add(customer);
            var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);

            string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void PutProduct(string customerID, Customer customer)
        {
            customer.CustomerID = customerID;
            if (!repository.Update(customer))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void DeleteProduct(string customerID)
        {
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            repository.Remove(customerID);
        }
    }
static readonly ICustomerRepository repository = new CustomerRepository();

here my repository is hard code. how can i inject it by unity.

please show me the way. thanks


Viewing all articles
Browse latest Browse all 4850

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>