简体   繁体   English

在C#控制台应用程序中访问dbContext

[英]Accessing dbContext in a C# console application

I have tried to figure this out, but I am stuck. 我试图弄清楚这一点,但我被困住了。

I have a Net Core 2 application with Service/Repo/Api/Angular layers - but now I want to 'bolt on' a console application and access all the goodies I have already built up. 我有一个带有Service / Repo / Api / Angular层的Net Core 2应用程序-但是现在我想“附加”控制台应用程序并访问我已经建立的所有好东西。 I seem to be in a mess of static objects and DI and null parameters. 我似乎陷入了混乱的静态对象和DI和null参数。 Anyway, here is a simplified version of my code. 无论如何,这是我的代码的简化版本。

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;

        }
    }

}

I am getting the classic 我正在经典

'An object reference is required for the non-static field' “非静态字段需要对象引用”

error. 错误。 Then from investigating on here I changed things to static and then everything becomes null. 然后,从这里进行研究,我将其更改为静态,然后一切都变为空。

It's not just the DbContext I am trying to inject. 我尝试注入的不仅是DbContext。 I'm also trying to inject 我也在尝试注入

private ManagerService _managerService; 私人ManagerService _managerService;

but getting same errors. 但出现相同的错误。

Update 更新资料

If I try 如果我尝试

private static ApplicationDbContext _appDbContext = new ApplicationDbContext(); 私有静态ApplicationDbContext _appDbContext = new ApplicationDbContext();

as suggested a few times below, then I get the error 如下面几次建议,那么我得到了错误

There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext( DbContextOptions )' 没有给出与'ApplicationDbContext.ApplicationDbContext( DbContextOptions )'所需的形式参数'options'相对应的参数

OK, I have figured this out, and I'll post my answer for anyone else struggling in this situation. 好的,我已经弄清楚了,我会将答案发布给在这种情况下苦苦挣扎的其他人。

When you launch the console app, your normal startup.cs doesn't execute, so you have to put a lot of that code in your console app. 启动控制台应用程序时,不会执行常规的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();
    }

and now your _appDbContext will be available throughout the rest of your console app. 现在,您的_appDbContext在整个控制台应用程序的其余部分都可用。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM