我正在使用一个.Net WinForms应用程序,该应用程序旨在从MongoDB收集记录并将记录插入到SQL Server数据库中。
我下面得到的错误在Application.Run(...)中标记
系统操作无效异常:'无法从根提供程序解析'FixSqlChatHistory.WinForm.MongoReader',因为它需要作用域服务'FixSqlChatHistory.DataContext. MongoToSqlContext ''
我使用的代码是
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var host = CreateHostBuilder().Build();
ServiceProvider = host.Services;
Application.Run(ServiceProvider.GetRequiredService<MongoReader>());
}
public static IServiceProvider ServiceProvider { get; private set; }
static IHostBuilder CreateHostBuilder()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => x.GetName().Name.Contains("FixSqlHistory"));
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => {
services.AddScoped<IMongoReader, MongoService>();
services.AddScoped<IChatActivityReader, ChatDataFixService>();
services.AddScoped<IChatActivityWriter, ChatDataFixService>();
services.AddAutoMapper(assemblies);
services.AddDbContext<MongoToSqlContext>(options => options.
UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
services.AddScoped<MongoReader>();
});
}
MongoReader(Form)的结构如下
public MongoReader(
MongoToSqlContext databaseContext,
IChatActivityReader chatActivityReader,
IChatActivityWriter chatActivityWriter,
IMongoReader mongoReader)
{
_databaseContext = databaseContext;
_chatActivityReader = chatActivityReader;
_chatActivityWriter = chatActivityWriter;
_mongoReader = mongoReader;
InitializeComponent();
}
自从我创建WinForms应用程序以来已经很长时间了,而且是第一次在IdeNet6中创建,所以我希望能在我出错的地方得到一些帮助。
我已经看过这里,这似乎是一个类似的问题,但我设置与AddScoped作为这篇文章建议
Cannot resolve 'ServiceBusConsumer' from root provider because it requires scoped service DbContext
1条答案
按热度按时间tez616oj1#
您需要手动create scope:
或者注册具有相应生存期的所有内容(
AddDbContext
允许指定不同于默认Scoped
的上下文生存期)。请注意,根据应用程序的不同,您可能不希望在其整个生命周期内使用相同的上下文。