2016-11-29 30 views
2

我試圖弄清楚EF-Core存在一些問題。
我使用MVC Core應用程序中的啓動代碼來初始化數據庫上下文。
這是我的DB背景:獲取數據訪問層內的Db上下文

public class AccountsDBContext : DbContext 
{ 
    public AccountsDBContext(DbContextOptions<AccountsDBContext> options) 
     :base(options) 
    { 

    } 

    // ... 

}

和啓動代碼:

public void ConfigureServices(IServiceCollection services) 
{ 
     // Inject the account db 
     services.AddDbContext<AccountsDBContext>(options => 
      options.UseMySQL(Configuration.GetConnectionString("AccountsStore"))); 

     // ... 

在所有exampes我看到DB Context是通過構造一個傳送到控制器(我假設通過依賴注入)並從那裏到其他實體\層。

[Route("api/[controller]")] 
public class AccountsController : Controller 
{ 
    private AccountsDBContext _db; 

    public AccountsController(AccountsDBContext context) 
    { 
     this._db = context; 
    } 

但是,我不是很喜歡db context將成爲控制器成員的想法。
我真的更喜歡在數據訪問層中獲取數據庫上下文,而不是將其傳遞到存儲庫類中。
有沒有辦法讓數據訪問層內的上下文?(據我所知,那裏沒有IServiceCollection,IApplicationBuilder,IServiceScopeFactory)

+1

你應該注入你的DAL到控制器中,並且在你的DAL中構造函數期望EF上下文作爲依賴。 .Net Core的內置DI應該能夠輕鬆解決這兩個問題。請參閱https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection – haim770

+0

如果您想在DAL中獲得(創建)dbcontext,只需在startup.cs中初始化DAL.DbContextFactory,並讓DbContextFactory在正確的時間創建dbcontext。請參見[http://stackoverflow.com/a/40837070/7045253](http://stackoverflow.com/a/40837070/7045253) –

+0

@ haim770示例非常棒。謝謝。 – Yaron

回答

0

我明白你要做什麼。我已經完成了。關鍵是在使用IServiceCollection的DAL中創建一個靜態類。那麼在這裏添加您的上下文這裏是我的,它的工作原理把我的前端甚至不知道實體框架,nethier做我的業務層:

public static IServiceCollection RegisterRepositoryServices(this IServiceCollection services) 
    { 
     services.AddIdentity<ApplicationUser, IdentityRole<int>>(
      config => { config.User.RequireUniqueEmail = true; 
       config.Cookies.ApplicationCookie.LoginPath = "/Account/Login"; 
       config.Cookies.ApplicationCookie.AuthenticationScheme = "Cookie"; 
       config.Cookies.ApplicationCookie.AutomaticAuthenticate = false; 
       config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents() 
       { 
        OnRedirectToLogin = async ctx => 
        { 
         if (ctx.Request.Path.StartsWithSegments("/visualjobs") && ctx.Response.StatusCode == 200) 
         { 
          ctx.Response.StatusCode = 401; 
         } 
         else 
         { 
          ctx.Response.Redirect(ctx.RedirectUri); 
         } 
         await Task.Yield(); 
        } 
       }; 
      }).AddEntityFrameworkStores<VisualJobsDbContext, int>() 
      .AddDefaultTokenProviders(); 

     services.AddEntityFramework().AddDbContext<VisualJobsDbContext>(); 

     services.AddScoped<IRecruiterRepository, RecruiterRepository>(); 
     services.AddSingleton<IAccountRepository, AccountRepository>(); 

     return services; 
    } 

然後我服務層我還有一個靜態類。我的服務層到存儲庫層中的參考,我在這裏註冊庫服務(自舉庫到服務層),像這樣,然後我在UI再次做同樣的:

服務層代碼:

public static class ServiceCollectionExtensions 
{ 
    public static IServiceCollection RegisterServices(this IServiceCollection services) 
    { 
     services.RegisterRepositoryServices(); 
     services.AddScoped<IRecruiterService, RecruiterService>(); 
     services.AddSingleton<IAccountService, AccountService>(); 

     return services; 
    } 
}