azure WebJobApp中EF上下文的依赖注入

sdnqo3pr  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(134)

我正在尝试创建我的第一个需要使用Entity Framework的webjobapp。我正在尝试将我的上下文注入到应用的构建器中,但是我收到了一个错误:

  • 无法将参数“db”绑定到类型ApplicationDbContext。请确保绑定支持参数Type * Web上有多个示例,但Azure WebJob的版本似乎变化很快,我找不到适用于我正在使用的版本的示例。这些是我正在使用的包版本:网络工作3.0 EF.NET核心7.0面向.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();
    
    }
}

项目档案

<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>
relj7zay

relj7zay1#

一开始连我也犯了同样的错误。

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。

相关问题