在构造函数中具有参数的Autfac注入服务

问题描述 投票:0回答:1

我了解如何使用autofac docs中的TypedParameter将可为空的参数注入构造函数。我正在努力了解如何将该服务注入参数将来自的另一服务。这是一些示例代码:

// interface
pubic Interface IProvider 
{
    string GetParameter();
}

// implementation
public class Provider : IProvider
{
    private readonly int? _parameterId;
    public Provider(int? parameterId){
        _parameterId = parameterId;
    }
    public string GetParameter(){
         // go get my parameter from wherever using int that was passed to constructor
    }
}

现在在我的api控制器中,我可能会注入此服务,以便我可以获取参数:

public class ParameterController : ApiController
{
    private readonly IProvider _provider;
    public ParameterController(IProvider provider){
         _provider = provider;
    }
    [HttpGet]
    public string GetParameterNoInput(){
         _provider.GetParameter(null);
    }
    [HttpGet]
    public string GetParameter(int input){
        // my provider wants this input but not as a passed parameter
        // I don't know how to do this
    }
 }

当然还有注册

builder.RegisterType<Provider>().As<IProvider>().InstancePerRequest()
   .WithParameter(new TypedParameter(typeof(Guid?), "parameterId"));

FWIW,我知道这不是一个很好的设计选择,但这是我要决定的。在autofac中处理此问题的模式是什么?要澄清的是,要规定的部分是IProvider注入了可空的int parameterId,而不是使用接受int的暴露方法。

我应该在控制器中做这样的事情吗?

Func<int?>, IProvider _newProvider;
public ParameterController(Func<int?, IProvider> provider){
    _newProvider = provider;
}

// and then in my api i can do
[HttpGet]
public string GetParameter(int input){
    var provider = _newProvider(input);
    provider.GetParameter();
}

我了解如何使用autofac文档中的TypedParameter将可为空的参数注入构造函数。我正在努力了解如何将该服务注入另一个服务,其中...

c# dependency-injection autofac
1个回答
1
投票

Autofac允许您在注册服务时传递参数。就您而言,看起来像这样

© www.soinside.com 2019 - 2024. All rights reserved.