我试图在Azure函数v3中使用依赖注入。我使用了Microsoft在以下文章中推荐的启动方法:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
这个事件是正确的触发,这是伟大的。然后,我将调用跨多个项目类型使用的依赖解析助手。
我使用Scrutor扫描程序集,这样就不必手动将每个接口添加到类(AddTransient等)中。这在ASP.NET Core项目中非常有用,但是对于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函数,所以我想知道这种类型的应用程序是否不可能使用程序集扫描。任何帮助都将不胜感激!
谢谢
更新08/09/2020
我在使用Scrutor进行组装扫描时仍然有问题,这与在运行时加载dll的方式有关--我相信,但我不能100%肯定这一点。最后,我不得不按照标准的Microsoft文档手动注册服务/类型。斯克鲁特能够在其他地方工作,但不能为Azure函数工作。我希望我做错了什么,但没能找到解决办法。
发布于 2019-10-29 16:25:32
谢谢你的建议@HariHaran。
我尝试使用Autofac,并设法使它与我的ASP .NET Core3.0WebAPI项目一起使用。Autofac提供的程序集扫描不起作用,所以我不得不使用扫描调用程序集来获取我自己的dll。我无法添加您在注释(AzureFunctions.Autofac)中提到的AzureFunctions.Autofac包,因为它与Autofac.Extensions.DependencyInjection之间存在版本冲突。
通过对上述Autofac过程进行新的程序集扫描,我再次尝试使用内置的.NET核心容器和清理器。这是我能够创建的帮助方法-这个方法适用于Web项目和Azure函数:-
用于Azure函数的启动类
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(MyNamespace.Gateway.Queue.Function.Startup))]
namespace MyNamespace.Gateway.Queue.Function
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSolutionServices();
}
}
}Web和Azure函数使用的DI助手
using Scrutor;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Microsoft.Extensions.DependencyInjection
{
public static class DotNetCoreBootstrapper
{
public static void AddSolutionServices(this IServiceCollection services)
{
string path = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
List<Assembly> assemblies = new List<Assembly>();
foreach (string dll in Directory.GetFiles(path, "MyNamespace*.dll"))
{
assemblies.Add(Assembly.LoadFrom(dll));
}
services.Scan(scan => scan
.FromAssemblies(assemblies)
.AddClasses(classes => classes.Where(types =>
types.FullName.StartsWith("MyNamespace.")))
.UsingRegistrationStrategy(RegistrationStrategy.Append)
.AsMatchingInterface()
.WithTransientLifetime()
);
}
}
}https://stackoverflow.com/questions/58540037
复制相似问题