使用 .Net Core web api 将控制台应用程序项目添加到解决方案

Adding console app project to a solution with .Net Core web api

我添加了对 Web api 项目的引用。将以下内容添加到 Program.cs

class Program
{
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder();
        BuildConfig(builder);

        var host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddDbContext<ModelContext>(
                    options => options.UseOracle(connectionString)); // dbcontext from web api project
                services.AddTransient<IEmailReminderService, EmailReminderService>();
            }).Build();

        var svc = ActivatorUtilities.CreateInstance<EmailReminderService>();

        var er = new EmailReminderService();
        er.OpenIncidentReminder();
    }
    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
            .AddEnvironmentVariables();

        _configuration = builder.Build();
    }
}

我得到 System.NullReferenceException:'Object reference not set to an instance of an object.'

_context 为空。

编辑

public class EmailReminderService : IEmailReminderService
    {
        private ModelContext _context;
        //private readonly IExceptionLogService _exceptionLogService;

        public EmailReminderService(ModelContext con)
        {
            _context = con;
            //_exceptionLogService = exceptionLogService;
        }

        public void OpenIncidentReminder()
        {
            var openIncidents = _context.Incidents.ToList();

        }
}

@terodaktil 关于 DbContext 的配置是正确的。您需要正确配置它以指定提供程序。有关此主题,请参阅 Microsoft's docs

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) => {
            // here i'm using in-memory DB, you'd use SqlServer, Oracle, etc.
            services.AddDbContext<AppDbContext>(o => o.UseInMemoryDatabase("db"));
            services.AddTransient<IEmailReminderService, EmailReminderService>();
        }).Build();

就是说,您需要创建一个范围来解析像 DbContext 这样的范围服务。 那么就可以直接使用作用域的服务提供者来解析IEmailReminderService,或者ActivatorUtilities.CreateInstance来创建具体实现的实例EmailReminderService.

using var scope = host.Services.CreateScope();

// now you can resolve the dbcontext
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

// or any service that depends on a scoped service
var reminder = scope.ServiceProvider.GetRequiredService<IEmailReminderService>();
// var reminder = ActivatorUtilities.CreateInstance<EmailReminderService>(scope.ServiceProvider);

reminder.OpenIncidentReminder();

参考文献: