代码之家  ›  专栏  ›  技术社区  ›  monstertjie_za

使用Autofac在我的组件类Azure函数中注入ILogger实例

  •  2
  • monstertjie_za  · 技术社区  · 7 年前

    我已经安装了 AzureFunctions.Autofac DI 图书馆。

    我设置了以下 AutofacConfig 类来注册我的类型:

    public class AutofacConfig
    {
        public AutofacConfig(string functionName)
        {
            DependencyInjection.Initialize(builder =>
            {
                //do all of you initialization here
    
                //db client
                builder.RegisterType<EventComponent>()
                .As<IComponent<EventModel>>().SingleInstance(); 
            }, functionName);
        }
    }
    

    EventComponent 类,我想将 ILogger

    public class EventComponent : IComponent<EventModel>
    {
        private ILogger _log;
    
        public EventComponent(ILogger logger)
        {
            _log = logger;
        }
    }
    

    下面是如何注入EventComponent:

    [FunctionName("AddEvent")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, ILogger log, [Inject]IComponent<EventModel> component)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
    
            await component.Add(new EventModel() { Id = Guid.NewGuid(), Description = $"Test description nr: {new Random().Next(1, 100000)}", User = "Test User" });
    
            return req.CreateResponse(HttpStatusCode.OK);
        }
    

    问题是,我在上面有个例外,因为 Autofac 无法解析参数Microsoft.Extensions.Logging文件伊洛格先生。

    以下是异常消息:

    异常绑定参数“component”。。。无法解析参数'Microsoft.Extensions.Logging文件构造函数Void.ctor的.ILogger logger(Microsoft.Extensions.Logging文件伊洛格先生。(有关详细信息,请参见内部异常。)—>找不到具有“”的构造函数Autofac.Core.Activators公司.反射.DefaultConstructorFinder'打开类型'事件.功能.组件.EventComponent'可以用可用的服务和参数调用:\r\n无法解析参数'Microsoft.Extensions.Logging文件构造函数Void.ctor的.ILogger logger(Microsoft.Extensions.Logging文件.ILogger)“,

    实例到我的 事件组件

    2 回复  |  直到 7 年前
        1
  •  2
  •   Gaurav Madaan    7 年前

    在Azure函数V2中,默认情况下会注入ILogger。另外,这里有两篇关于Azure函数中依赖注入的非常好的文章。 https://blog.mexia.com.au/dependency-injections-on-azure-functions-v2

    http://codingsoul.de/2018/01/19/azure-function-dependency-injection-with-autofac/

        2
  •  0
  •   SamiR    7 年前

    因为我认为这是不可能的。ILogger日志是由框架注入的,我不知道如何从AutofacConfig类引用它。

    我解决这个问题的方法是将EventComponent类更改为使用Setter注入而不是构造函数注入,如下所示:

    public class EventComponent : IComponent<EventModel>
    {
        public ILogger Log { get; set; }    
    }
    

    并更改函数以设置日志属性:

    [FunctionName("AddEvent")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, ILogger log, [Inject]IComponent<EventModel> component)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            component.Log = log;
            await component.Add(new EventModel() { Id = Guid.NewGuid(), Description = $"Test description nr: {new Random().Next(1, 100000)}", User = "Test User" });
    
            return req.CreateResponse(HttpStatusCode.OK);
        }
    

    缺点是您需要记住在每个使用该类的函数开始时设置该值,但是注入是有效的。

    推荐文章