2016-11-30 61 views
0

我有一點使用Xamarin.Forms的依賴注入方面的經驗,但不是在WebApi中,我想要的是通過我的接口發送數據並在我的類中執行爲實現該接口,還有就是我有:如何使用Microsoft Asp.net創建依賴注入WebApi

public interface IRepository 
{ 
    IHttpActionResult SendContext(user user); 
    IHttpActionResult GetContextData(int id); 
} 

public class ContextGoneBase : ApiController,IRepository 
{ 
    public IHttpActionResult GetContextData(int id) 
    { 
     try 
     { 
      using (var context = new GoneContext()) 
      { 
       var result = context.user.Where(a => a.id_user == id).Select(w => 
       new { w.user_name, w.cellphone_number, w.user_kind, w.CEP, w.area.area_name, w.district, w.city.city_name, w.city.state.state_name }); 
       var list = result.ToList(); 

       if (list != null) 
       { 
        return Ok(list); 
       } 
       else 
       { 
        return BadRequest(); 
       } 
      } 
     } 
     catch (Exception) 
     { 
      return BadRequest(); 
     } 
    } 

而且在我的控制器,我試圖做這樣的事情:

[Route("86538505")] 
    public IHttpActionResult GetData(int id, IRepository repo) 
    { 
     this._repo = repo; 
     var result = _repo.GetContextData(id); 
     return result; 
    } 

但是,它失敗!謝謝!

回答

0

您應該將IRepository作爲參數傳遞給構造函數 將IRepository類型的字段_repo設置爲傳遞參數的值。

public ContextGoneBase (IRepository repository){ //Constructor 

    _repo = repository; 

} 

。而再使用像統一的IOC容器實例與大家團結使用的NuGet你將有一個UnityConfig類文件,並有您可以註冊庫安裝後的權利parameters.For例如控制器type.For例如,如果你的版本庫的類型庫中,然後

public static class UnityConfig 
     { 
      public static void RegisterComponents() 
      { 

// register all your components with the container here 
      // it is NOT necessary to register your controllers 

      // e.g. container.RegisterType<ITestService, TestService>(); 
       var container = new UnityContainer(); 
       container.RegisterType<IRepository,Repository>(); 

       GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); 
      } 
     } 
在Global.asax中

現在調用這個方法:

protected void Application_Start() 
     { 

      UnityConfig.RegisterComponents(); 

     }