Search code examples
c#dependency-injectionunity-container

Injection Constructor Dependency Injection with parameters


I am trying to understand how do I resolve multiple parameters being passed to a constructor from a DI container.

I have an interface IDataAccess (#1) and a class called SQL implementing IDataAccess (#2). Another class ObjectBroker (#3) that supplies the Instance of any concrete class that implements interface. I am using unity container for constructor dependency injection as shown in (#4).

All this works well, until I try to add more parameters to the ObjectBorker constructor. For example if I do this --> public ObjectBroker(IDataAccess da, string s), then I am not able to understand how do I resolve the parameters for the DI container?

    //region #1  
    public interface IDataAccess
    {
        string GetDataBaseName();
    }
    //endregion


    //region #2  
    public class SQL : IDataAccess 
    {

        public string GetDataBaseName()
        {
            return "Data retrieved from SQL, Microsoft";
        }
    }
    //endregion

    //region #3  
    public class ObjectBroker 
    {
        private IDataAccess dataAccess;
        
        public ObjectBroker(IDataAccess da)  //Fails if I have public ObjectBroker(IDataAccess da, string s)
        {
            dataAccess = da;
        }
        public string GetDataBaseName()
        {
            return dataAccess.GetDataBaseName();
        }
    }
    //endregion

    //region #4 
    IUnityContainer iuContainer3 = new UnityContainer();            
    iuContainer3.RegisterType<IDataAccess, SQL>("SQL");

    var con = new InjectionConstructor(iuContainer3.Resolve<IDataAccess>("SQL"));
    iuContainer3.RegisterType<BusinessFactory>("SQL", con);
    //endregion

Tried this var con = new InjectionConstructor(iuContainer3.Resolve(new ResolverOverride[] { new ParameterOverride("da", "SQL"), new ParameterOverride("s", "PSQL") }));

But getting an error Unity.ResolutionFailedException: 'Resolution failed with error: No public constructor is available for type DependencyInjection.IDataAccess


Solution

  • Solution using InjectionConstructor:

    var con = new InjectionConstructor(iuContainer3.Resolve<IDataAccess>("SQL"), "PSQL");
    iuContainer3.RegisterType<ObjectBroker>("SQL", con);
    

    InjectionConstructor instantiated with two parameters:

    • iuContainer3.Resolve<IDataAccess>("SQL") which will be mapped to da constructor parameter.
    • PSQL which will be mapped to s constructor parameter.

    Here is an interactive full example.

    Solution using InjectionFactory:

    iuContainer3.RegisterType<ObjectBroker>("SQL", new InjectionFactory(CreateDataAccessLayer));
    
    private static IDataAccess CreateDataBaseLayer(IUnityContainer container)
    {
        var da = container.Resolve<IDataAccess>();
        return new ObjectBroker(da, "PSQL");
    }