如何在运行时使用EF和Structuremap更改连接字符串?

时间:2018-09-18 14:11:11

标签: c# asp.net-mvc entity-framework structuremap

我正在.net MVC Web应用程序中进行开发,并且正在使用EF(DB FIRST)来获取数据:

    public class LocationManager: MyNetworkEntities,  ILocationManager
    {
        private readonly MyNetworkEntities _dbContext = new MyNetworkEntities();

        public LocationManager(MyNetworkEntities context, string connection)
        {
            // extension for changing connectionstring at runtime
            if(connection != null)
            context.ChangeDatabase
                    (
                        dataSource: connection 
                    );


        _dbContext = context;
    }

    public List<Locations> GetAll()
    {
        return _dbContext.Locations.ToList();
    }
}

也使用structuremap:

public DefaultRegistry() {
    Scan(
        scan => {
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
            scan.With(new ControllerConvention());
        });
    For<ILocationManager>().Use<LocationManager>();
}

我的控制器:

public class UserController : Controller
{
    private readonly ILocationManager _locationManager;

    public UserController(ILocationManager locationManager)
    {
        _locationManager = locationManager;
    }
    // GET: User
    public ActionResult Index()
    {
        var t = _locationManager.GetAll();
        return View("UserManagment");
    }
}

问题:

由于我想在运行时更改db-connectionstring,我该怎么做 使用结构图时?

类似的东西:

string myNewConnection = "connection";
 var t = _locationManager.setConnection(myNewConnection).GetAll();

我该怎么做?

注意:上面的代码不完整,我仍在尝试解决此问题。

1 个答案:

答案 0 :(得分:1)

我猜您的EF Core DbContext看起来像这样:

public MyDbContext(DbContextOptions<MyDbContext> options)
    : base(options)
{
}

在这种情况下,您只需创建DbContext(不必在任何地方使用DI)并将其指向您需要的数据库:

var connectionString = ...
var builder = new DbContextOptionsBuilder<MyDbContext>().UseSqlServer(connectionString);
var context = new MyDbContext(builder.Options);
var locations = context.Locations.ToList();

当然,您可以实现更复杂的功能,例如创建指向您需要的DbContext的工厂类,并通过DI注册该工厂以通过构造函数注入机制获得该工厂。工厂将采用以下方法:

// This is a pseudo code below
factory.CreateDbContext (.. some parameters to detect which DB to use ..)
相关问题