是否可以将 IAgent 接口注入 .net 核心 DI 容器

Is is possible to inject to .net core DI container the IAgent interface

我正在使用 NewRelic 来深入了解我的系统,为了将自定义属性添加到新遗迹的交易中,我正在使用 NewRelic.Api.Agent.NewRelic.GetAgent() 解析 IAgent 接口(docs)

喜欢:

public async Task<IActionResult> MyMethod([FromBody]MyRequest request)
{
    //Do Some logic.

    IAgent agent = NewRelic.Api.Agent.NewRelic.GetAgent();
    ITransaction transaction = agent.CurrentTransaction;
    transaction.AddCustomAttribute("MyCustomAttribute", SomeValue)

    return Ok(...);
}

是否可以使用依赖注入容器来解析IAgent接口?喜欢:

[ApiController]
public class MyController
{
    private readonly IAgent _agnet;
    public MyController(IAgent agent)
    {
        _agent = agent;
    }

    public async Task<IActionResult> MyMethod([FromBody]MyRequest request)
    {
         //Do Some logic.

         ITransaction transaction = this._agent.CurrentTransaction;
         transaction.AddCustomAttribute("MyCustomAttribute", SomeValue)

         return Ok(...);
    }
}

因此它是一个静态实例,它可以注册为单例:

services.AddSingletone<IAgent>(NewRelic.Api.Agent.NewRelic.GetAgent());

或:

services.AddSingletone(NewRelic.Api.Agent.NewRelic.GetAgent());

不要忘记先配置代理,然后将其添加到 IServiceCollection