Disambiguating multiple constructors in UnityContainer.Resolve

Jan 5, 2011 at 6:02 PM

I am just now learning Unity and, to be honest, a little lost right now. I was able to get it to inject a custom type with a single constructor, but it is unable to disambiguate if I have more than one... and I am not sure what I need to do to get around this.

(FYI, I am trying to get it to return something equeivilent to "this.impl = new EmployerMedAuth(IoC)" in the code below)

Mainline code is:

public class EmployerMedAuthSvc : EmployerBase, IEmployerMedAuth
{
    private IEmployerMedAuth impl;
    private IUnityContainer IoC;

    public EmployerMedAuthSvc()
    {
        IoC = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();

        Logger = IoC.Resolve<LogWriter>();
        TraceMgr = IoC.Resolve<TraceManager>();

        IoC.RegisterType<IEmployerMedAuth, EmployerMedAuth>();
        this.impl = IoC.Resolve<IEmployerMedAuth>();
    }
}

Instantiating:

public class EmployerMedAuth : EmployerBase, IEmployerMedAuth
{
    private readonly IEmpMedAuthRepository repository;

    public EmployerMedAuth(IEmpMedAuthRepository repository)
    {
        this.repository = repository;
    }

    public EmployerMedAuth(UnityContainer IoC)
    {
        Logger = IoC.Resolve<LogWriter>();
        TraceMgr = IoC.Resolve<TraceManager>();

        IoC.RegisterType<IEmpMedAuthRepository, SqlEmpMedAuthRepository>();
        this.repository = IoC.Resolve<IEmpMedAuthRepository>();
    }

    public EmployerMedAuth()
    {
        var IoC = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();

        Logger   = IoC.Resolve<LogWriter>();
        TraceMgr = IoC.Resolve<TraceManager>();

        IoC.RegisterType<IEmpMedAuthRepository, SqlEmpMedAuthRepository>();
        this.repository = IoC.Resolve<IEmpMedAuthRepository>();
    }
}

Jan 6, 2011 at 1:08 AM

You'll want to ask this over on the Unity forum. What you want is completely possible, but I see some major design flaws with what you're doing. But discussing it over there will bring in the more DI specific people rather than general Entlib stuff.