如何防止自动发现DbConfiguration

时间:2019-07-11 09:07:10

标签: c# entity-framework entity-framework-6

我在一个包含200多个项目的解决方案中,其中一个应用程序需要自定义DbConfiguration,例如:

    public class MyDbConfiguration : DbConfiguration
    {
        public MyDbConfigurationDbConfiguration()
        {
            SetExecutionStrategy("System.Data.SqlClient", 
                () => new SqlAzureExecutionStrategy());
        }
    }

但是,当我介绍它时,它被发现到单元测试的后期(无论如何它都不适用)。我确实在应用程序入口处以编程方式初始化配置,因此一切都可以在生产环境中进行:

DbConfiguration.SetConfiguration(new Office2EntityFrameworkDbConfiguration());

但是100个左右的单元测试项目没有切入点(我相信更改所有DbContext(大约70个左右)或所有单元测试的设计都是不好的( 15000左右)以确保此不需要的DbConfiguration尽快初始化。

System.InvalidOperationException: The default DbConfiguration instance was used by the Entity Framework before the 'MyDbConfiguration' type was discovered. An instance of 'MyDbConfiguration' must be set at application start before using any Entity Framework features or must be registered in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.
   ved System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
   ved System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
   ved System.Data.Entity.DbContext.InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model)
   ved System.Data.Entity.DbContext..ctor(DbConnection existingConnection, Boolean contextOwnsConnection)

1 个答案:

答案 0 :(得分:0)

好几天我对此感到困惑。看来MyDbConfiguration仅在与DbContext本身位于同一程序集中时才被检测到(并且可能也在DbContext实例化的程序集中)。

我最终要做的是将MyDbConfiguration移到它自己的项目中,这将是唯一的课程。而且有效!