2013-03-19 27 views
1

我試圖用統一爲每本文注入的依賴:的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控制器的每個實例都通過無參數構造函數完成。

回答

0

您沒有爲控制器指定生命週期。 MSDN states

如果不指定壽命的值,實例將有 默認的容器控制的壽命。它將在每次調用Resolve時返回一個參考 到原始對象。

如果IUnitOfWork依賴是瞬態的,那麼控制器也應該是瞬態的。所以試試

unity.RegisterType<CustomerController>(new TransientLifetimeManager()); 

這可能不能解決整個問題,但它聽起來像是它的一部分。你當然不應該需要無參數的構造函數。

+0

感謝您的回覆,但即使在更改生命期後,我仍然會得到相同的行爲。我檢查了我正在解除的文章,他正在使用HierarchicalLifetimeManager。 – 2013-03-19 14:39:45

0

我有這個,因爲我使用這個返回我的依賴範圍的解析器,然後將容器放置在dispose中。所以在第一次請求後,容器被丟棄了。

0

看起來像是因爲你沒有爲Unity容器使用單例模式。

有一個私有的靜態變量,而不是var container = new UnityContainer();

internal static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => new UnityContainer()); 

然後在代碼中使用.Value屬性進行訪問。

+0

這不適合我。以隨機的方式,我的默認構造函數被調用... – 2017-09-27 11:31:34