跟上。net 6的速度,并试图使用DI和控制台应用程序获得一个工作示例。当启动时,我得到一个错误,试图获得对我的服务类的引用。我错过了什么?
系统。InvalidOperationException: '没有类型'ConsoleEfcore的服务。StoreCtxFactory'已注册'
Program.cs
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ConsoleEfcore;
using ConsoleEfcore.StoreModels;
Console.WriteLine("Hello, World!");
// get settings from config file
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false);
IConfiguration config = builder.Build();
var Option1 = config.GetSection("TestSettings:Option1");
string Opt = Option1.Value;
var SvcBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(configure => configure.AddConsole())
.AddScoped<IStoreFactory, StoreCtxFactory>();
});
var host = SvcBuilder.Build();
DoStuff(host.Services);
host.Run();
static void DoStuff(IServiceProvider services)
{
using IServiceScope serviceScope = services.CreateScope();
IServiceProvider provider = serviceScope.ServiceProvider;
StoreCtxFactory store = provider.GetRequiredService<StoreCtxFactory>();
// lets test
StoreContext ctx = store.GetStoreContext();
int prodCount = ctx.Products.Count();
Console.WriteLine($"We have {prodCount} products");
}
StoreCtxFactory.cs
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleEfcore.StoreModels;
using Microsoft.EntityFrameworkCore;
namespace ConsoleEfcore
{
public interface IStoreFactory
{
public StoreContext GetStoreContext() ;
}
public class StoreCtxFactory : IStoreFactory
{
private IConfiguration _config;
private readonly DbContextOptionsBuilder<StoreContext> _bldr;
private StoreContext _ctx;
public StoreCtxFactory(IConfiguration config)
{
_config = config;
_bldr = new DbContextOptionsBuilder<StoreContext>();
_bldr.UseSqlServer(_config.GetConnectionString("StoreConn"), sqlOptions => sqlOptions.CommandTimeout(600).EnableRetryOnFailure());
_ctx = new StoreContext();
}
public StoreContext GetStoreContext()
{
StoreContext retval = _ctx;
return retval;
}
}
}
您注册了抽象
//...
.AddScoped<IStoreFactory, StoreCtxFactory>()
//...
,但试图解决与实现。
StoreCtxFactory store = provider.GetRequiredService<StoreCtxFactory>();
重构以使用注册抽象
//...
IStoreFactory store = provider.GetRequiredService<IStoreFactory>();
//...
将停止错误