[英]Dependency injection of EF context in WebJobApp
我正在尝试创建我的第一个需要使用实体框架的 webjobapp。 我试图将我的上下文注入到应用程序的构建器中,但出现错误:
无法将参数“db”绑定到类型 ApplicationDbContext。 确保绑定支持参数类型web 上有几个示例,但 Azure WebJob 的版本似乎变化很快,我找不到适用于我正在使用的版本的示例。 这些是我正在使用的 package 版本: Webjobs 3.0 EF.NET Core 7.0 Targeting .NET 7.0
这是我的代码:
class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
builder.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
});
builder.ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("My full connection string"));
services.AddTransient<IEmailSender, EmailSender>();
});
var host = builder.Build();
using (host)
//{
await host.RunAsync();
}
}
}
public class Functions
public static void Sendemails([TimerTrigger("0 0 20 * * SUN-THU")] TimerInfo timer,
ILogger logger, ApplicationDbContext db)
{
var mylist = db.Users.ToList();
}
}
我尝试使用以下代码而不是上面的代码来配置服务。 在检查构建器时,我可以看到服务已添加到构建器中。 但是在调用 builder.Build() 之后检查主机,服务不会出现在主机容器中。
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
.....
builder.ConfigureServices((context, sc) => sc= serviceCollection);
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
.....
private void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")))
}
项目文件
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.33" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings" Version="1.5.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
<PackageReference Include="SendGrid" Version="9.28.1" />
</ItemGroup>
</Project>
最初即使我也遇到了同样的错误。
在Program.cs
中做了一些更改。
我的程序.cs:
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
class Program
{
static async Task Main()
{
var builder = new HostBuilder()
.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
})
.ConfigureLogging((context, b) =>
{
b.AddConsole();
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
})
.ConfigureServices(services =>
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer("MyDefaultConnection"));
services.AddTransient<ApplicationDbContext, ApplicationDbContext>();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
如果您在本地运行,请交叉检查一次local.settings.json
文件。
我的local.settings.json
:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
我的appsettings.json
:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "Storage Account Connection String"
}
}
也看看SO Thread一次。
参考资料取自MSDoc 。
我从头开始做这些步骤。
1-
public class ApplicationDbContext: IdentityDbContext<User, Role, Guid>
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
}
2-在appsettings.json中添加
"ConnectionStrings": {
"SqlServer": "Data Source=;Initial Catalog=SpaceManagment;User ID=sa;Password=654321;MultipleActiveResultSets=true;TrustServerCertificate=True;Connection Timeout = 60"
},
3-
在program.cs中添加
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options
.UseSqlServer(settings.SqlServer);
//Tips
// .ConfigureWarnings(warning => warning.Throw(RelationalEventId.QueryClientEvaluationWarning));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.