Microsoft.Practices.Unity.ResolutionFailedException InvalidOperationException - The type String cannot be constructed

Aug 21 at 7:56 PM
I have an Asp.Net MVC application (4.5) that is using Unity 4.0.1 and Unity.MVC 4.0.1 with a constructor DI for each of the controller classes. Generally, everything is work fine except sporadically and usually under a modest load of concurrent users were experiencing this error requiring us to restart IIS to have the web server resume functioning. When this occurs 100% of http requests return with this same 500 error of
Microsoft.Practices.Unity.ResolutionFailedException
Resolution of the dependency failed, type = "APP1Cloud.Services.IClientDBService", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value. ----------------------------------------------- At the time of the exception, the container was: Resolving APP1Cloud.Services.ClientDBService,(none) (mapped from APP1Cloud.Services.IClientDBService, (none)) Resolving parameter "connection" of constructor APP1Cloud.Services.ClientDBService(System.String connection) Resolving System.String,(none)

Stack Trace is: 
  Microsoft.Practices.Unity.UnityContainer.DoBuildUp(System.Type, System.Object, System.String, System.Collections.Generic.IEnumerable`1<Microsoft.Practices.Unity.ResolverOverride>) 
   Microsoft.Practices.Unity.UnityContainer.DoBuildUp(System.Type, System.String, System.Collections.Generic.IEnumerable`1<Microsoft.Practices.Unity.ResolverOverride>) 
   Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[[System.__Canon, mscorlib]](Microsoft.Practices.Unity.IUnityContainer, Microsoft.Practices.Unity.ResolverOverride[]) 
  APP1Cloud.Models.ApplicationDbContext.Create() 
   Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2+<Invoke>d__0[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].MoveNext() 
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage+<RunApp>d__5.MoveNext() 
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext+<DoFinalWork>d__2.MoveNext() 
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(System.IAsyncResult) 
   System.Web.HttpApplication+AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 
   System.Web.HttpApplication.ExecuteStep(IExecutionStep, Boolean ByRef)
In effect, Unity is failing to resolve all IClientDBServices and the only way to get it functioning again is to restart IIS.

Our UnityConfig class is implemented as:
public class UnityConfig
    {
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }

        public static void RegisterTypes(IUnityContainer container)
        {
            
                          container.RegisterType<IMasterDBService, MasterDBService>(
                "tenant_session",
                new PerRequestLifetimeManager(),
                new InjectionFactory(c =>
                    new MasterDBService("MasterDBConnection"))
                    );

                           container.RegisterType<ITenantService, TenantService>(
                                                        new PerRequestLifetimeManager(),
                                    new InjectionConstructor(
                                          new ResolvedParameter<IMasterDBService>("tenant_session")
                                        )
                           );

                            container.RegisterType<IClientDBService, ClientDBService>(
                    new PerRequestLifetimeManager(),
                    new InjectionFactory(c =>
                    {
                        var tenant = c
                            .Resolve<ITenantService>()
                            .Current;
                        if (tenant != null && !string.IsNullOrEmpty(tenant.ConnectionString))
                                return new ClientDBService(tenant.ConnectionString);
                        return new ClientDBService("MasterDBConnection");
                    })
                );
       }
}
an example for how all our controller classes are implemented using a constructor DI:
public class ActualController : Controller
    {
        private readonly IClientDBService sdService;

        public ActualController(IClientDBService sdService)
        {
            this.sdService = sdService;
        }
       [HttpPost]
        public virtual ActionResult SaveActualTime(int actualId, string inTime, string outTime)
        {
            Actual actual = sdService.GetActual(actualId);                     

            TimeSpan actualInTime   = DateTime.ParseExact(TimeHelper.TwoDigitHourTimeString(inTime), "hh:mm tt", null).TimeOfDay;
            TimeSpan actualOutTime  = DateTime.ParseExact(TimeHelper.TwoDigitHourTimeString(outTime), "hh:mm tt", null).TimeOfDay;

            actual.ClassBunkID  = actual.ClassBunkID;
            actual.InTime       = actualInTime;
            actual.OutTime      = actualOutTime;
            actual.EditDate     = DateTime.Now;
            actual.EditedBy_Id  = User.Identity.GetUserId();

            sdService.UpdateActual(actual);

            string json = JsonConvert.SerializeObject(new { success = true }, Formatting.None).ToString();
            return Content(json, "application/json");
        }
}
Our TenantService class is responsible for producing the current db connection string that the client is logged into at the moment. Our application is supporting a situation users of the applications will login and look up the underlying databases they are working with to read and write data through this. So each client has its own tenant database.
public class TenantService : ITenantService
    {
        private readonly IMasterDBService masterDbService;
        private readonly HttpContextBase context;

        public TenantService(IMasterDBService masterDbService)
        {
            this.context = new HttpContextWrapper(HttpContext.Current);
            this.masterDbService = masterDbService;
        }

        public Tenant Current
        {
            get
            {
                if (context != null && context.Session != null && context.Session[SessionNames.SpecificTenantName] != null)
                {
                    var tenant = FindByHost((string)context.Session[SessionNames.SpecificTenantName]);
                    if (tenant != null)
                        tenant.DisableSeedMigrations = true;  
                    else
                        throw new Exception(string.Format("TenantService.Current - Session SpecificTenantName '{0}' FindbyHost return a null."));
                    return tenant;
                }
            }
       }
      
        public Tenant FindByHost(string clientName)
        {
            return masterDbService.LookupTenant(clientName);
        }
 }
public class MasterDBService : IMasterDBService
    {
        private string _connection = "";
        private MasterDBContext masterDB = null;

        public MasterDBService(string connection)
        {
            this._connection = connection;
            this.masterDB = new MasterDBContext(connection);
        }

        public Tenant LookupTenant(string clientName)
        {
            return masterDB.Tenants.FirstOrDefault(t => t.Name == clientName);
        }
        public string LookupClientDBConnection(string clientName)
        {
            var tenant = LookupTenant(clientName);
            if (tenant != null)
                return tenant.ConnectionString;
            else
                throw new Exception(string.Format("Unable to lookup client '{0}'", clientName));
        }

        public Tenant AddTenant(Tenant tenant)
        {
            Tenant newTenant = masterDB.Tenants.Add(tenant);
            masterDB.SaveChanges();
            newTenant.TenantUsers = new List<TenantUser>();
            return newTenant;
        }
}
    public class MasterDBContext : DbContext
    {
        public MasterDBContext(string connection)
            : base(connection)
        {
            this.Database.CommandTimeout = 180;
        }

        public DbSet<Tenant> Tenants { get; set; }
}