2016-04-21 44 views
2

正如標題所述。我正在創建一個Web API,並且在我的API控制器中,我試圖在構造函數中聲明一個存儲庫。我成功聲明瞭它,但是我嘗試在該控制器中調用的每個API方法都會返回500錯誤。當我刪除構造函數/庫變量時,我沒有問題。.NET Core - 嘗試向我的API控制器添加存儲庫,但是當我做每個控制器方法時都會返回500錯誤

控制器

[Route("api/[controller]")] 
public class TestController: Controller 
{ 
    private ITestRepository _testRepository; 

    public TestController(ITestRepository testRepository) 
    { 
     _testRepository= testRepository; 
    } 

    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    // Add framework services. 
    services 
     .AddMvcCore() 
     .AddJsonFormatters() 
     .AddApiExplorer(); 

    services.AddScoped<ITestRepository , TestRepository >();  
    services.AddSwaggerGen(); 
} 

我缺少的東西?

+1

什麼是確切的錯誤信息? – CodeNotFound

+0

@CodeNotFound這只是一個500內部服務器錯誤。沒有其他信息給出。我試圖在控制器級調試它,但調試器在崩潰之前甚至沒有到達 – Daath

+3

您的存儲庫類是否有一個參數較少的構造函數?向我們顯示代碼? – CodeNotFound

回答

2

簡答

我想聲明的構造函數庫。我成功聲明瞭它,但是我嘗試在該控制器中調用的每個API方法都會返回500錯誤。當我刪除構造函數/庫變量時,我沒有問題。

你可能需要做出的一個變化:

  1. 從資源庫中的構造函數中刪除參數,或
  2. 寄存器存儲庫的構造函數接受服務。

說明

確切的代碼從你的問題適用於下列庫代碼。

public interface ITestRepository { } 

public class TestRepository : ITestRepository { } 

但是,如果構造函數接受參數,代碼將拋出500錯誤。

public class TestRepository : ITestRepository 
{ 
    public TestRepository(object someObject) 
    { 

    } 
} 

它拋出與構造,因爲services.AddScoped<ITestRepository, TestRepository>()打電話要求TestRepository構造符合這兩個標準之一。

  1. 構造函數不帶參數,或
  2. 一個構造函數解析服務。

所以修復您的代碼,你需要做的一個變化:

  1. 從構造函數中刪除參數,或
  2. 註冊你的構造函數接受服務。

例如,如果存儲庫在其構造函數中接受了DbContext,那麼您的代碼可能如下所示。

啓動。CS

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddMvcCore() 
     .AddJsonFormatters() 
     .AddApiExplorer(); 

    services 
     .AddEntityFramework() 
     .AddInMemoryDatabase() 
     .AddDbContext<TestDbContext>(); // register a service 

    services.AddScoped<ITestRepository, TestRepository>(); 
    services.AddSwaggerGen(); 
} 

TestRepository.cs

public class TestRepository : ITestRepository 
{ 
    // pass the registered service to the ctor 
    public TestRepository(TestDbContext testDbContext) 
    { 

    } 
} 
2

首先,我們使用註冊的Microsoft.practices.Unity依賴組件,和第二,我們解決這些問題,我們都使用它們。

在使用它之前,你還沒有解決你的依賴。

public class TestController: Controller 
{ 
    private ITestRepository _testRepository; 

    public TestController(ITestRepository testRepository) 
    { 
     _testRepository= testRepository; 
    } 

    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

註冊這裏:

DIContainer.Instance.RegisterType<ITagManager, TagManager>(); 

我們使用它們之前解決我們的依賴。

DIContainer.Instance.Resolve<ITagManager>().RetrieveTwitterTags(); 
相關問題