gpt4 book ai didi

c# - 配置 Unity 以解析构造函数参数和接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:56 25 4
gpt4 key购买 nike

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

public FaxService(string phone, IFaxProvider faxProvider)

Unity 如何配置为第一个参数发送字符串,第二个参数发送 IFaxProvider 实例?我意识到我可以注入(inject)另一个提供字符串的服务,但我正在寻找一个解决方案,我不必更改 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 { }

但是它抛出...

Unity.Exceptions.ResolutionFailedException HResult=0x80131500
Message=Resolution of the dependency failed, type = 'ConsoleApp3.IFaxService', name = '(none)'. Exception occurred while: while resolving.

enter image description here

最佳答案

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>();

关于c# - 配置 Unity 以解析构造函数参数和接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com