Add a DbProviderFactory without an App.Config

前端 未结 8 1748
无人共我
无人共我 2020-12-13 06:52

I am using DbProviderFactories in my data layer (based on Entity Framework) and am using SQLite for my database, but I don\'t have to have a App.Config to have the following

8条回答
  •  醉梦人生
    2020-12-13 07:28

    Update for EF 6.0+

    You can add a DbProviderFactory by registering a IDbDependencyResolver and resolving for the type DbProviderFactory. An example of this is below:

    static class Program
    {
        [STAThread]
        static void Main()
        {
            System.Data.Entity.DbConfiguration.Loaded += (_, a) => {
                a.AddDependencyResolver(new MyDependencyResolver(), true);
            };  
    
            Application.Run(new Form1());
        }
    }
    
    class MyDependencyResolver : System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver {
    
        public object GetService(Type type, object key) {
    
            // Output the service attempting to be resolved along with it's key 
            System.Diagnostics.Debug.WriteLine(string.Format("MyDependencyResolver.GetService({0}, {1})", type.Name, key == null ? "" : key.ToString()));
    
            if (type == typeof(System.Data.Common.DbProviderFactory)) {
    
                // Return whatever DbProviderFactory is relevant
                return new MyDbProviderFactory(); 
    
            }else if(type == typeof(System.Data.Entity.Infrastructure.IProviderInvariantName) && key != null && key == "MyDbProviderFactory"){
    
                // Return the Provider's invariant name for the MyDbProviderFactory
                return new MyProviderInvariantName();
    
            }
    
            return null;
        }
    
        public IEnumerable GetServices(Type type, object key) {
            return new object[] { GetService(type, key) }.ToList().Where(o => o != null);
        }
    }
    
    
    

    you may have to resolve for some additional types as well depending upon what type of overriding you're needing to do and how your project is setup. Basically just start with the code above and continue to debug until you've determined all the services you need to resolve for given your specific requirements.

    You can read more about EF dependency resolution at the links below:

    • http://msdn.microsoft.com/en-us/data/jj680697.aspx
    • https://entityframework.codeplex.com/wikipage?title=EF%20Configuration%20and%20Extensibility
    • https://entityframework.codeplex.com/wikipage?title=Rebuilding%20EF%20providers%20for%20EF6

    Additionally, you can do this configuration by overriding DbConfiguration as described in the first link above.

    提交回复
    热议问题