我试图弄清楚这一点,但我被困住了。
我有一个带有 Service/Repo/Api/Angular 层的 Net Core 2 应用程序——但现在我想“固定”一个控制台应用程序并访问我已经构建的所有好东西。我似乎陷入了一堆静态对象以及 DI 和 null 参数中。无论如何,这是我的代码的简化版本。
namespace SimpleExample
{
class Program
{
private static ApplicationDbContext _appDbContext;
public Program(ApplicationDbContext appDbContext)
{
_appDbContext = appDbContext;
}
static void Main(string[] args)
{
var instance = new Program(); // this doesn't work!
var instance = new Program(_appDbContext); // neither does this!
instance.GetData();
}
private void GetData()
{
Console.WriteLine("Let's read some data! Press a key to continue.");
Console.ReadLine();
var data = "my data";
var result = GetId(data);
}
private string GetId(string original)
{
var data = _appDbContext.Data
.Where(x => x.Name == original.Trim)
.FirstOrDefault();
return data;
}
}
}
我得到了经典
'An object reference is required for the non-static field'
错误。然后从这里的调查开始,我将事物更改为静态,然后一切都变为空。
我尝试注入(inject)的不仅仅是 DbContext。我也在尝试注入(inject)
private ManagerService _managerService;
但得到同样的错误。
更新
如果我尝试
private static ApplicationDbContext _appDbContext = new ApplicationDbContext();
正如下面几次建议的那样,我得到了错误
There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)'
最佳答案
好的,我已经弄清楚了,我会为在这种情况下苦苦挣扎的其他人发布我的答案。
当您启动控制台应用程序时,您的正常 startup.cs 不会执行,因此您必须在控制台应用程序中放置大量代码。
private static SiteService _siteService;
private static ApplicationDbContext _appDbContext;
public static void Main()
{
var services = new ServiceCollection();
services.AddTransient<ISiteInterface, SiteRepo>();
services.AddTransient<SiteService>();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("blah-blah"));
var serviceProvider = services.BuildServiceProvider();
_siteService = serviceProvider.GetService<SiteService>();
_appDbContext = serviceProvider.GetService<ApplicationDbContext>();
GetData();
}
现在你的 _appDbContext 将在您的控制台应用程序的其余部分中可用。
希望有帮助!
关于c# - 在 C# 控制台应用程序中访问 dbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49972591/