簡體   English   中英

在沒有EF Core參考的ASP.NET項目中使用EF存儲嗎?

[英]Using EF stores in an ASP.NET project without EF Core reference?

將默認ASP.NET標識與EF Core結合使用的推薦方法是將以下內容放入ASP.NET應用程序的Startup類的ConfigureServices方法中:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

這需要AddEntityFrameworkStores似乎不屬於ASP.NET Web項目(表示層項目)的東西:對EF Core的引用(以獲取AddEntityFrameworkStores擴展方法),以及對ApplicationDbContext的引用(我d認為應該在持久層的數據訪問代碼內部)。

在仍然使用此配置作為我的網站身份的同時,如何避免這些引用並適當地分離關注點?

值得注意的是,在.NET Core中,引用是可傳遞的。 這意味着,如果WebProj引用BLLProjBLLProj引用DALProj

WebProj -> BLLProj -> DALProj

然后WebProj仍然從DALProj獲取所有引用。

話雖如此,您可以使用AddDbContext擴展方法在代碼中起作用的相同方式,將此配置委派給數據項目。 這意味着該Web項目將沒有任何直接引用到任何DAL對象。

例如,在您的BLL層甚至是一個完全獨立的項目中,您都可以使用擴展方法將服務添加到DI容器中,例如:

public static class ServiceCollectionExtensions
{
    public static void AddDataAndIdentity(this IServiceCollection services, IConfiguration config)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                config.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
    }
}

並在您的Web項目中,在ConfigureServices方法中調用它:

services.AddDataAndIdentity(Configuration);

此外,還有一些工具可以幫助您可視化項目依賴性。 如果您擁有Visual Studio Enterprise版本,則可以創建一個代碼映射 其他工具(例如ReSharper)也可以提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM