2016-09-09 51 views
0

我想在ASP.NET Core WebApi項目中使用n層體系結構。我在DAL層(類庫項目)中定義了一些帶有接口的Repository。然後我試圖通過使用IServiceCollection這種方式來注入這樣的:
ASP.NET核心。如何使用n層體系結構?

 public void ConfigureServices(IServiceCollection services) 
     { 
      // Add framework services. 
      services.AddMvc(); 
      services.AddScoped<IUsersRepository, UsersRepository>(); 
     } 

但這不能得到解決。我在這裏做錯了什麼?

+0

您的UsersRepo本身是否需要依賴關係,並且該依賴關係尚未註冊? 您應該能夠獲得有助於指出的錯誤消息。 –

+0

@MikeD,這個回購沒有新東西。我曾經多次創建它,並且像以前一樣,我期望應用DI容器將Repo實例注入到控制器中。 –

+2

通常repos需要一個dbContext類型的對象,你確定你的repo在它自己的構造函數中沒有任何參數? –

回答

0

配置您的Startup.cs:

public void ConfigureServices(IServiceCollection services) { 
... 
    services.AddSingleton<ISessionFactory>(c => { 
    var config = new Configuration(); 
    ... 
    return config.BuildSessionFactory(); 
    }); 
... 
    services.AddSingleton<RoleServico>(); 
... 
} 

然後,在你的API控制器使用這樣的:

[Route("api/role")] 
public class RoleController : Controller { 

    private readonly ISessionFactory SessionFactory; 
    private readonly RoleServico RoleServico; 

    public RoleController(ISessionFactory sessionFactory, RoleServico roleServico) { 
     if (sessionFactory == null) 
     throw new ArgumentNullException("sessionFactory"); 
     SessionFactory = sessionFactory; 
     this.RoleServico = roleServico; 
    } 

    [HttpGet] 
    public IList<RoleModel> Get() { 
     IList<RoleModel> model = new List<RoleModel>(); 
     using (var session = SessionFactory.OpenSession()) 
     using (var transaction = session.BeginTransaction()) { 
     return RoleServico.SelecionarRoles(session); 
     } 
    } 
} 

你Startup.cs看起來不錯,但我不知道你怎麼」重新使用你的注入類,或者,如果你得到一些錯誤信息。

「RoleServico」是類庫項目中的類(與您的情況類似)。在我的情況下,我使用「Singleton」,但它是「Scoped」的相同配置。我不能評論你的問題,並要求提供更多信息(我沒有50聲望)。