![](/img/trans.png)
[英]How to create a class library that can use any Ef Core DbContext
[英]How to use DbContext of Webpplication in the Class library
我正在使用 .net core 3.1,並且在 Web 應用程序中配置了 AppDbContext。 我有另一個類庫項目,在里面我添加了 Webapplication 的引用。 如何在類庫中使用 Web App Dbcontext?
我嘗試在類中創建 AppDbContext 的實例,如下所示。
public class CallService { private readonly IServiceProvider _service; private readonly AppDbContext _context; public CallService(AppDbContext context,IServiceProvider service) { _context = context; _service = service; } //... //... }
這段代碼存在多個問題。
如果您想在控制台應用程序和 Web 中使用相同的代碼,您應該將其提取到類庫中。 之后,您應該將來自 Web 和控制台應用程序的引用添加到您的類庫中。將來自控制台應用程序的引用添加到 Web 應用程序是錯誤的。
要正確執行此操作,您應該使用依賴項注入系統。
首先,您需要為您的服務創建一個接口。 然后,您可以在類庫項目中定義另一個類,該類將添加該類庫中的所有依賴項。
public static class DomainModuleDependencies{
public static IServiceProvider AddDomainDependencies(this IServiceCollection services){
//... add any dependency here
services.AddTransient<AppDbContext>();
services.AddTransient<ICallService,CallService>();
}
}
然后你可以打電話給服務商,給你你需要的服務
var services = new ServiceCollection();
services.AddDomainDependencies();
var serviceProvider = services.BuildServiceProvider();
var callService = services.GetService<ICallService>();
callServices.CallMethod();
聽起來很復雜,但將來如果您需要添加另一個服務,您可以創建並將其添加到依賴項中。 通過這種方式,您將盡可能地遵循 SOLID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.