【发布时间】:2020-02-20 17:09:57
【问题描述】:
我正在尝试在 Azure Functions v3 中使用依赖注入。我使用了 Microsoft 在以下文章中推荐的启动方法:-
https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
事件正在正确触发,这很棒。然后我调用了一个我在多个项目类型中使用的依赖解析助手。
我使用 Scrutor 来扫描程序集,这样我就不必手动将每个接口添加到类(AddTransient 等)。这在 ASP.NET Core Web API 项目中效果很好,但在 Azure 函数中根本不起作用。我的解决方案依赖项根本没有添加。
这是我的代码:-
public static void AddSolutionServices(this IServiceCollection services)
{
services.Scan(scan => scan
.FromCallingAssembly()
.FromApplicationDependencies()
.AddClasses(classes => classes.Where(types => types.FullName.StartsWith("MyNamespace.")))
.UsingRegistrationStrategy(RegistrationStrategy.Append)
.AsMatchingInterface()
.WithTransientLifetime()
);
}
这是我第一次尝试编写 Azure 函数,所以我想知道这种类型的应用程序是否无法使用程序集扫描。任何帮助将不胜感激!
谢谢
2020 年 8 月 9 日更新
我仍然在使用 Scrutor 进行程序集扫描时遇到问题,我相信这与运行时加载 dll 的方式有关,但我对此不是 100% 确定的。我最终不得不按照标准的 Microsoft 文档手动注册服务/类型。 Scrutor 能够在其他任何地方工作,但不能用于 Azure Functions。我希望我做错了什么,但无法找到解决方案。
【问题讨论】:
-
你可以尝试使用nuget.org/packages/AzureFunctions.Autofac而不是
Scrutor -
我希望能够坚持使用 .NET Core 容器,而不是使用其他容器。
-
Autofac 有更好的社区和功能,它同时支持 .NET Core 和 Framework
标签: c# dependency-injection .net-core azure-functions