配置 Unity 解析构造函数参数和接口

Joh*_*ore 3 .net c# inversion-of-control unity-container

我有一个带有两个构造函数参数的 FaxService 类。

public FaxService(string phone, IFaxProvider faxProvider)
Run Code Online (Sandbox Code Playgroud)

Unity 如何配置为发送第一个参数的字符串和第二个参数的 IFaxProvider 实例?我意识到我可以注入另一个提供字符串的服务,但我正在寻找一种不必更改 FaxService 构造函数参数的解决方案。

这就是我到目前为止所拥有的......

class Program
{
    static void Main(string[] args)
    {
        var container = new UnityContainer();

        var phone = "214-123-4567";
        container.RegisterType<IFaxProvider, EFaxProvider>();
        container.RegisterType<IFaxService, FaxService>(phone);

        var fax = container.Resolve<IFaxService>();
    }
}

public interface IFaxService { }

public interface IFaxProvider { }

public class FaxService : IFaxService
{
    public FaxService(string phone, IFaxProvider faxProvider) { }
}

public class EFaxProvider : IFaxProvider { }
Run Code Online (Sandbox Code Playgroud)

但它抛出...

Unity.Exceptions.ResolutionFailedException HResult=0x80131500
Message=依赖关系解析失败,类型=“ConsoleApp3.IFaxService”,名称=“(无)”。while:解决时发生异常。

在此输入图像描述

Alw*_*ing 5

var container = new UnityContainer();
var phone = "214-123-4567";
container.RegisterType<IFaxProvider, EFaxProvider>();
container.RegisterType<IFaxService, FaxService>(new InjectionConstructor(phone, typeof(IFaxProvider)));

var fax = container.Resolve<IFaxService>();
Run Code Online (Sandbox Code Playgroud)