简体   繁体   English

带有 Unity 的实体框架“底层提供程序在 Open 上失败”。

[英]Entity framework with Unity “The underlying provider failed on Open.”

I'm working on upgrading one of my companies projects to newer versions of MVC, Entity Framework and Unity.我正在努力将我的公司项目之一升级到新版本的 MVC、Entity Framework 和 Unity。 Most of the work has been completed however, I do have this problem when loading data from the database.大部分工作已经完成,但是从数据库加载数据时我确实遇到了这个问题。 This does not happen on every request and most of the application functions normally.这不会发生在每个请求上,并且大多数应用程序功能正常。 The problem occurs on API calls the application does when there are a couple of concurrent calls.当有几个并发调用时,应用程序执行的 API 调用会出现此问题。

I've tried switching the LifeTimeManager of the Unity containers to different types with different results (none of them actually fixed the problem).我尝试将 Unity 容器的 LifeTimeManager 切换为不同类型,但结果不同(它们都没有真正解决问题)。

This is my DataContext class这是我的数据上下文 class

    public class DataContext : IUnitOfWork, IRepositoryFactory
    {
        private const string CONSTRING = "CONSTRING";
        private static volatile DbContext dbContext = new DbContext(CONSTRING);

        private static volatile ConcurrentBag<object> repositories = new ConcurrentBag<object>();

        public DbContext DbContext => dbContext;

        public DataContext()
        {
            Database.SetInitializer<DbContext>(null);
        }

        public void SaveChanges()
        {
            dbContext.SaveChanges();
        }

        public void Dispose()
        {
            dbContext.Dispose();
        }

        public IRepository<T> CreateRepositoryFor<T>() where T : class, IEntity
        {

            var reposType = typeof(Repository<T>);

            var repos = (IRepository<T>)repositories.FirstOrDefault(r => r.GetType() == reposType);

            if (repos == null)
            {
                repos = new Repository<T>(dbContext.Set<T>());


                repositories.Add(repos);
            }

            return repos;
        }

    }

This is my UnityConfig这是我的 UnityConfig

    public class UnityConfig
    {
        #region Unity Container
        private static readonly Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Configured Unity Container.
        /// </summary>
        public static IUnityContainer Container => container.Value;
        #endregion

        public static void RegisterTypes(IUnityContainer container)
        {
            RegisterDependencies(container);

            System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolverAdapter(container));
            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }

        private static void RegisterDependencies(IUnityContainer unityContainer)
        {
            RegisterDataContextAndUnitOfWork(unityContainer);
            RegisterRepositories(unityContainer);
        }

        private static void RegisterDataContextAndUnitOfWork(IUnityContainer container)
        {
            container.RegisterType<IUnitOfWork, DataContext>(new ContainerControlledLifetimeManager());
            container.RegisterType<IRepositoryFactory, DataContext>(new ContainerControlledLifetimeManager());
            container.RegisterType<IChangeTracker, DataContext>(new ContainerControlledLifetimeManager());
            container.RegisterType(typeof (ICrudService<>), typeof (GenericCrudService<>));

        }

        private static void RegisterRepositories(IUnityContainer container)
        {
            // Haal MethodInfo op zodat we at runtime de static RegisterRepository<T> kunnen aanroepen
            var registerRepositoryMethodName = MemberNameHelper.GetActionName(() => RegisterRepository<IEntity>(container));
            var registerRepositoryMethodInfo = typeof(UnityConfig).GetMethod(registerRepositoryMethodName, BindingFlags.NonPublic | BindingFlags.Static);

            // Registreer een repository voor iedere IEntity class in Domain project
            foreach (var entityType in typeof(IEntity).Assembly.GetTypes().Where(t => typeof(IEntity).IsAssignableFrom(t)))
            {
                var registerRepositoryMethod = registerRepositoryMethodInfo.MakeGenericMethod(entityType);
                registerRepositoryMethod.Invoke(null, new object[] { container });
            }
        }

        private static void RegisterRepository<T>(IUnityContainer unityContainer) where T : class, IEntity
        {
            unityContainer.RegisterFactory<IRepository<T>>(
                factory => factory.Resolve<IRepositoryFactory>().CreateRepositoryFor<T>(),
                new ContainerControlledLifetimeManager()
            );
        }
    }

The connectionstring is: Data Source=LOCALHOST;Initial Catalog=Database;Integrated Security=true;MultipleActiveResultSets=True连接字符串为: Data Source=LOCALHOST;Initial Catalog=Database;Integrated Security=true;MultipleActiveResultSets=True

The error message is: The underlying provider failed on Open.错误消息是: The underlying provider failed on Open.

call dbContext.Connection.Open();调用dbContext.Connection.Open(); method after initialize your dbContext variable.初始化dbContext变量后的方法。 This will open connection for EF这将为 EF 打开连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架给出异常:“底层提供程序在打开时失败。” - Entity Framework giving exception : “The underlying provider failed on Open.” 基础提供程序在打开时失败。 MVC - The underlying provider failed on Open. MVC 实体框架异常“底层提供程序打开失败” - Entity Framework Exception “The underlying provider failed on Open” 基础提供程序在实体框架中打开时失败 - The underlying provider failed on Open in entity framework connection 基础提供程序无法打开-WPF和实体框架 - The underlying provider failed to open - WPF and Entity FrameWork 实体框架底层提供程序在打开时失败 - Entity Framework The underlying provider failed on Open System.Data.Entity.Core.EntityException:“基础提供程序在打开时失败。” 错误? - System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.' Error? 在Parallel.ForEach中:基础提供程序在打开时失败。 使用EF5 - in Parallel.ForEach : The underlying provider failed on Open. with EF5 内部异常 #1:MSG:底层提供程序在打开时失败。 在服务器上 - INNER EXCEPTION #1: MSG: The underlying provider failed on Open. On Server 错误:基础提供程序在打开时失败。 怎么解决呢? - Error: The underlying provider failed on Open. How to resolve it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM