在program.cs中,我创建了一个配置服务方法
private static void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton(new LoggerFactory()
.AddSerilog());
serviceCollection.AddLogging();
serviceCollection.AddDbContext<Spiderdb>(options => options.UseSqlite("Data Source=(localdb)\\ProjectsV13;Initial Catalog=SpiderDB1;Integrated Security=True"));
// Initialize serilog logger
Log.Logger = new LoggerConfiguration()
.WriteTo.File("app.log")
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
serviceCollection.AddTransient<App>();
}
这就是我使用/注射的方式
class App
{
private readonly ILogger<App> _logger;
private readonly Spiderdb _spiderDb;
public App(ILogger<App> logger, Spiderdb context)
{
_logger = logger;
_spiderDb = context;
}
public async void RunAsync()
{
_logger.LogInformation("Starting App");
using (_spiderDb)
{
var x = await _spiderDb.ProxyServersProviders.ToListAsync();
}
}
}
如果我不注入并且使用SQLServer而不是SQLlite,但使用DI时,相同的连接字符串也可以正常工作。模型和上下文的类是使用EF电动工具构建的,但这很可能是一个红色鲱鱼,对于SQL lite,连接字符串不正确,还是我没有正确注入/注册?
奇怪的是,日志中提到为创建了“ IServiceProvider” 实体框架内部使用。我确定我在某个地方见过&与DI有关吗?
2018-07-21 06:42:39.004 +01:00 [DBG] An 'IServiceProvider' was created for
internal use by Entity Framework.
2018-07-21 06:42:39.101 +01:00 [INF] Starting App
2018-07-21 06:42:40.160 +01:00 [INF] Entity Framework Core 2.1.1-rtm-30846
initialized 'Spiderdb' using provider
'Microsoft.EntityFrameworkCore.SqlServer' with options: None
2018-07-21 06:42:40.356 +01:00 [DBG] Compiling query model:
'from ProxyServersProvider <generated>_0 in DbSet<ProxyServersProvider>
select [<generated>_0]'
2018-07-21 06:42:40.413 +01:00 [DBG] Optimized query model:
'from ProxyServersProvider <generated>_0 in DbSet<ProxyServersProvider>
select [<generated>_0]'
2018-07-21 06:42:40.691 +01:00 [DBG] (QueryContext queryContext) =>
IAsyncEnumerable<ProxyServersProvider> _InterceptExceptions(
source: IAsyncEnumerable<ProxyServersProvider> _TrackEntities(
results: IAsyncEnumerable<ProxyServersProvider> _ShapedQuery(
queryContext: queryContext,
shaperCommandContext: SelectExpression:
SELECT [p].[Id], [p].[DailyReqCount], [p].[DailyReqLimit], [p].
[FailedCount], [p].[FirstReqToday], [p].[IsRestAPI], [p].[LastReq], [p].[URL]
FROM [ProxyServersProviders] AS [p],
shaper: UnbufferedEntityShaper<ProxyServersProvider>),
queryContext: queryContext,
entityTrackingInfos: { itemType: ProxyServersProvider },
entityAccessors: List<Func<ProxyServersProvider, object>>
{
Func<ProxyServersProvider, ProxyServersProvider>,
}
),
contextType: Spider.EF.Spiderdb,
logger: DiagnosticsLogger<Query>,
queryContext: queryContext)
2018-07-21 06:42:40.814 +01:00 [DBG] Opening connection to database
'SpiderDB1' on server '(localdb)\ProjectsV13'.
答案 0 :(得分:0)
您可以尝试使用这种格式。
serviceCollection.AddDbContext<Spiderdb>(options => options.UseSqlite("Server=(localdb)\\ProjectsV13;Database=SpiderDB1;Trusted_Connection=True"));
参考:https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings