我試圖用統一爲每本文注入的依賴:的Web API控制器參數的構造函數調用一次,參數的構造函數在後續請求
http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver
以下是我在我的世界。 ASAX
void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterType<CustomerController>();
unity.RegisterType<TPS.Data.Can.IUnitOfWork, TPS.Data.Can.EFRepository.UnitOfWork>(new HierarchicalLifetimeManager());
config.DependencyResolver = new IoCContainer(unity);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureApi(GlobalConfiguration.Configuration);
}
這裏是我的API控制器:
public class CustomerController : ApiController
{
private TPS.Data.Can.IRepository<tblCustomer> _repo;
private TPS.Data.Can.IUnitOfWork _uow;
public CustomerController() { }
public CustomerController(TPS.Data.Can.IUnitOfWork uow) {
_uow = uow;
_repo = uow.CustomerRepository;
}
// GET api/customer/5
public IEnumerable<Customer> Get()
{
string identity = HttpContext.Current.User.Identity.Name;
//REFACTOR THIS
if (String.IsNullOrWhiteSpace(identity))
identity = "chardie";
var customers = from c in _repo.Get()
where c.SalesRep == identity
select new Customer
{
IDCUST = null,
CustCode = c.CustCode,
CustName = c.CustName
};
return customers.ToList();
}
當我第一次開始調試我的應用程序時,這起作用。如果我在參數化的構造函數中設置了斷點,那麼當我第一次訪問Web API時會觸發斷點。當我在瀏覽器中刷新頁面時,構造函數確實調用而不是,因此不會注入依賴項,並且Get()操作會引發異常,因爲預期的存儲庫爲空。
任何人都可以告訴我爲什麼我的構造函數在第一次請求後沒有被調用嗎?
謝謝!
克里斯
編輯
FWIW,我完全是從Web API控制器中刪除了參數的構造函數,和我的第二個要求,我得到異常:
Type 'TPS.Website.Api.CustomerController' does not have a default constructor
因此,看起來我在第一個請求中注入了我的repo依賴項,但在此之後,Web API控制器的每個實例都通過無參數構造函數完成。
感謝您的回覆,但即使在更改生命期後,我仍然會得到相同的行爲。我檢查了我正在解除的文章,他正在使用HierarchicalLifetimeManager。 – 2013-03-19 14:39:45