提供程序 System.Data.Client 的 MEF 注册 EntityFramework.SqlServer

MEF register EntityFramework.SqlServer for provider System.Data.Client

我们有一个具有很多依赖项的多层应用程序。我们使用 Autofac 和 MEF,以便所有组件都可以在 init 模块中注册自己的依赖项。这样,"higher" 组件就不必知道所有的依赖关系图。它只注册它需要的组件,剩下的就来了。在更高的层次上,有一个 WCF facade 应用程序,它导入我们几乎所有的 DLL 并将它们注册到 Autofac。它工作正常,但由于存储库层依赖于 EntityFramework,我得到了臭名昭著的错误:

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file

我发现没有这个错误的唯一方法是在WCF facade项目中直接引用EntityFramework.SqlServer。但我想把这个责任留给回购层本身。所以我需要一种方法来加载 dll 并注册 System.Data.SqlClient。有谁知道这样做的方法还是我只是在做梦?这是我第一次同时使用 Autofac 和 MEF,我远不是 DI 专家。

由于它是高度概念化的,这里有一个带有源代码的小模式可以帮助您更好地理解:

获取可读版本 here

也许你可以看看Code-Based Configuration

  1. 创建自定义 DbConfiguration

    public class MyDbConfiguration : DbConfiguration 
    { 
        public MyDbConfiguration() 
        { 
            // Other configuration stuff like SetDefaultConnectionFactory
            SetProviderServices(
                "System.Data.SqlClient", 
                System.Data.Entity.SqlServer.SqlProviderServices.Instance);
        } 
    } 
    
  2. DbConfigurationTypeAttribute 添加到您的 DbContext

    [DbConfigurationType(typeof(MyDbConfiguration))] 
    public class MyDbContext : DbContext 
    { }
    

    [DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")] 
    public class MyDbContext : DbContext 
    { }
    
  3. 从 app.config 文件中删除 entityFramework 配置

编辑

对于查找 MEF 组件引用的程序集的顶级项目,如果您 able/willing 向 app.config 添加内容,也许您可​​以使用类似的内容:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="Libs"/>
  </assemblyBinding>
</runtime>

从某种意义上说,它仍然是一个依赖项,但是您必须为 MEF 添加一个搜索路径...

https://msdn.microsoft.com/en-us/library/823z9h8w%28v=vs.110%29.aspx
How can MEF resolve dependencies of assemblies that don't live at the root of the application?