简体   繁体   中英

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. I seem to be in a mess of static objects and DI and null parameters. 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. I'm also trying to inject

private ManagerService _managerService;

but getting same errors.

Update

If I try

private static 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 )'

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.

    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.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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