我们正在使用Unity.WebAPI在Web API中实现依赖项注入。
我想将Token
作为构造函数参数传递给实现类,而不是设置为属性?
还请帮助我改进以下架构。
UnityConfig
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<ICustomer, Customer>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
BaseController
public class BaseController : ApiController
{
protected string Token;
public BaseController()
{
if (System.Web.HttpContext.Current.Request.Headers["Authorization"] != null)
{
Token = System.Web.HttpContext.Current.Request.Headers["Authorization"];
}
}
}
CustomerController
public class CustomerController : BaseController
{
ICustomer CustomerRepository;
public CustomerController(ICustomer customerRepository)
{
CustomerRepository = customerRepository;
CustomerRepository.Token = base.Token;
}
[HttpGet]
[Route(UrlConstants.GETCUSTOMERDETAILS)]
public IHttpActionResult GetCustomerDetails(int customerId)
{
return Content(HttpStatusCode.OK, CustomerRepository.GetCustomerDetails(customerId));
}
}
界面
public interface IBase
{
string Token { get; set; }
}
public interface ICustomer : IBase
{
CustomerDetails GetCustomerDetails(int customerId);
}
实施
public class Customer : ICustomer
{
public string Token { get; set; }
public CustomerDetails GetCustomerDetails(int customerId)
{
// Use the Token here
}
}