Search code examples
c#.netinversion-of-controlunity-container

configure Unity to resolve a constructor parameter and interface


I have a FaxService class that takes two constructor parameters.

public FaxService(string phone, IFaxProvider faxProvider)

How is Unity configured to send a string for the first parameter and an IFaxProvider instance for the second? I realize I can inject another service that provides the string, but I am looking for a solution where I don't have to change the FaxService constructor parameters.

This is what I have so far...

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 { }

but it throws...

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


Solution

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