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

标签 c# .net inversion-of-control unity-container

我有一个带有两个构造函数参数的 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/

相关文章:

.net - 如何在 BackgroundWorker 中访问 COM 对象?

c# - 处理横切问题,例如 Web 应用程序组件的内部统计报告

c# - 查找特定子文件夹

c# - 不带主键的 LINQ DeleteOnSubmit

c# - Hash Algorithm 的 "Create"方法的文档是否有缺陷?

c# - 使用 DI 的单一方法委托(delegate) vs 接口(interface)

c# - System.NotSupportedException - 无法比较“System.Linq.IQueryable”类型的元素

c# - 每个接口(interface)都显式实现? (涉及国际奥委会)

entity-framework - 从 Entity Framework 上下文中删除失败的更改

c# - 如何限制 C# 中的文本框只接收数字和(点 "."或逗号 ","),在 "."或 ","之后只允许 2 个数字字符