繁体   English   中英

无法获得 Azure Function.Net 5.0 依赖注入以在具有依赖关系的另一个项目中注入服务

[英]Can't get Azure Function .Net 5.0 Dependency Injection to inject service in another Project with dependencies

我正在尝试将服务注入我的 Azure Function,它位于另一个项目中。

这是我的代码。

public static async Task Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults()
                .ConfigureServices(s =>
                {                    
                    s.AddTransient<ILocationService, LocationService>();                    
                })
                .Build();

            Console.WriteLine("Host running!");

            await host.RunAsync();            

        }

LocationService 依赖于 DBContext。

private readonly MyAppDBContext _context;

        public LocationService(MyAppDBContext context)
        {
            _context = context;
        }

这是我的 Function。

private readonly ILocationService _locationService;
private readonly TelemetryClient _telemetryClient;
    
    public Function1(ILocationService locationService, TelemetryConfiguration telemetryConfiguration)
    {
        _locationService = locationService;            
        _telemetryClient = new TelemetryClient(telemetryConfiguration);
    }

这是错误。

结果:失败异常:System.InvalidOperationException:尝试激活“MyApp.Services.LocationService”时无法解析“MyApp.Data.MyAppDBContext”类型的服务。 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(类型实现类型,CallSiteChain callSiteChain,ParameterInfo[] 参数,Boolean throwIfCallSiteNotFound) callSiteChain) 在

我已经尝试了 Microsoft.Extensions.DependencyInjection 的 6.0 和 5.0.2 版本。

本指南似乎表明我做对了。

https://learn.microsoft.com/en-us/azure/azure-functions/do.net-isolated-process-guide#dependency-injection

任何帮助深表感谢! 谢谢!

原来这是 Visual Studio 2019 的问题。我无法让 web 发布正常工作,所以我使用了 FTP。为此,我使用了发布到文件夹的方法。 然后我压缩文件并使用 Power Shell 上传 zip 文件。 事实证明,发布到文件夹的方法无法正常工作。 它从不更新文件。 我所做的所有更改都没有到达服务器。 太令人沮丧了。 我在这上面浪费了好几个小时。 这是现在正在工作的。 我还通过下载新的发布配置文件修复了 web 发布方法。

 s.AddDbContext<MyDBContext>();
 s.AddLogging();
 s.AddScoped<IMyService, MyService>();
 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM