-1

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

now I am doing things like this way without Unity DI.

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

1 Answers1

1

Dependency Injection in ASP.NET Web API 2

Constructor injection

public class CustomerController : ApiController {
    readonly ICustomerRepository repository;

    public CustomerController(ICustomerRepository repository) {
        this.repository = repository;
    }

    //...other code removed for brevity
}

Configure Unity for Web api

public class UnityConfiguration() {
   public IUnityContainer Config() {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<ICustomerRepository, CustomerRepository>();

        // return the container so it can be used for the dependencyresolver.  
        return container;         
   }
}

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {

        // Register Unity with Web API.
        var container = UnityConfiguration.Config();
        config.DependencyResolver = new UnityResolver(container);

        // Your routes...

    }
}

You also need a DependencyResolver:

public class UnityResolver : IDependencyResolver {
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container) {
        if (container == null) {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType) {
        try {
            return container.Resolve(serviceType);
        } catch (ResolutionFailedException) {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        try {
            return container.ResolveAll(serviceType);
        } catch (ResolutionFailedException) {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope() {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose() {
        container.Dispose();
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Hey @Nkosi, I have implemented excactly with the same way but getting at GetService method inside UnityResolver.cs class and error is --> "Resolution failed with error: No public constructor is available for type System.Web.Http.Metadata.ModelMetadataProvider. ", you have any idea about that? – Nadeem Shaikh Jul 28 '20 at 15:01