ASP.Net WebApi:如何通过Unity DI注入存储库 [英] ASP.Net WebApi: How to inject repository by Unity DI

查看:54
本文介绍了ASP.Net WebApi:如何通过Unity DI注入存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请与代码示例讨论如何通过Unity DI在控制器中动态注入存储库

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

现在,我在没有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);
    }
}

静态只读ICustomerRepository存储库=新CustomerRepository();

static readonly ICustomerRepository repository = new CustomerRepository();

这里我的存储库是硬代码.我怎么能统一注入它?

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

请给我指路.谢谢

推荐答案

ASP.NET Web API 2中的依赖注入

构造函数注入

public class CustomerController : ApiController {
    readonly ICustomerRepository repository;

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

    //...other code removed for brevity
}

为Web api配置Unity

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...

    }
}

您还需要一个 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();
    }
}

这篇关于ASP.Net WebApi:如何通过Unity DI注入存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆