微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 允许最终用户在运行时切换Entity Framework提供程序

考虑到我已使用.NET Core Web应用程序配置EF:
services.AddDbContext<ApplicationDbContext>(options => 
    options.UsesqlServer(...));

我也可以下载一个包来支持例如sqlite:

services.AddDbContext<ApplicationDbContext>(options =>
    options.Usesqlite(...));

我们如何允许用户在应用安装上“选择”提供商?我的意思是 – 例如,在wordpress中,您可以从下拉列表中进行选择.

这在.NET Core中是否可行?我看到的唯一方法是仅重启应用程序…

解决方法

这是一个关于如何实现DbContextFactory或DbContextProxy< T>的示例.这将创建正确的提供程序并返回它.
public interface IDbContextFactory
{
    ApplicationContext Create();
}

public class DbContextFactory() : IDbContextFactory,Idisposable
{
    private ApplicationContext context;
    private bool disposing;

    public DbContextFactory()
    {
    }

    public ApplicationContext Create() 
    {
        if(this.context==null) 
        {
            // Get this value from some configuration
            string providerType = ...;
            // and the connection string for the database
            string connectionString = ...;

            var dbContextBuilder = new DbContextOptionsBuilder();
            if(providerType == "MSsql") 
            {
                dbContextBuilder.UsesqlServer(connectionString);
            }
            else if(providerType == "sqlite")
            {
                dbContextBuilder.Usesqlite(connectionString);
            }
            else 
            {
                throw new InvalidOperationException("Invalid providerType");
            }

            this.context = new ApplicationContext(dbContextBuilder);
        }

        return this.context;
    }

    public void dispose(){
        dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void dispose(bool disposing){
        if (disposing){
            disposing?.dispose();
        }
    }
}

还要确保如上所示实现一次性模式,以便在工厂处置后立即处理上下文,以防止DbContext在内存中保留的时间超过必要时间并尽快释放非托管资源.

最后将工厂注册为作用域,就像上下文本身一样:

services.AddScopedd<IDbContextFactory,DbContextFactory>();

更先进和通用/可扩展的方法是通过创建IDbContextProxy< T>.使用一些反射来获取正确的构造函数和DbContextOptionsBuilder的类.

也可以创建一个抽象提供者创建的IDbContextBuilder.

public class sqlServerDbContextBuilder IDbContextBuilder
{
    public bool CanHandle(string providerType) => providerType == "sqlServer";

    public T CreateDbContext<T>(connectionString)
    {
        T context = ... // Create the context here

        return context;
    }
}

然后你可以选择没有硬编码if / else或switch块的正确提供者

// Inject "IEnumerable<IDbContextBuilder> builders" via constructor
var providerType = "sqlServer";
var builder = builders.Where(builder => builder.CanHandle(providerType)).First();
var context = builder.CreateDbContext<ApplicationContext>(connectionString);

添加新类型的提供程序就像添加依赖项和XxxDbContextBuilder类一样简单.

有关此方法和类似方法的更多信息,请参见here,herehere.

原文地址:https://www.jb51.cc/csharp/100413.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐