设置的DbContext的连接字符串中使用Ninject我的仓库类 [英] Setting the connection string of a DBContext in my repository class using Ninject

查看:305
本文介绍了设置的DbContext的连接字符串中使用Ninject我的仓库类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用EF 6,并实现与使用DI容器Ninject依赖注入库模式的MVC 5应用程序。为的DbContext的连接字符串存储在其中EF上下文正确地找到Web.config文件。一切工作正常。最近,我有一个要求,要我的DbContext的连接需要在运行时被确定并连接到不同的数据库(但具有完全相同的结构)。所以,我需要的库进行实例化之前到SQL的ConnectionString部分来自在运行时的ConnectionString实体改变。我真的AP preciate在做一些帮助。我不是一个DI大师;知道刚够Ninject让我的东西去。

I have an MVC 5 application that uses EF 6 and implements Repository pattern with dependency injection using the DI container Ninject. The connection string for the dbcontext is stored in the Web.config file which the EF Context properly finds. Everything works fine. Lately, I have a requirement that the connection to my DBContext need to be determined at runtime and connect to different databases (but with exactly the same structure). So, I need to change the sql connectionstring part from the entity connectionstring at run-time before the repository is instantiated. I would really appreciate some help in doing it. I am not a DI guru; know just enough Ninject to get my things going.

下面是我的仓库基本接口:

Here is my Repository Base Interface:

public interface IRepositoryBase<T> where T : class
{
    void Add(T entity, string userGuid = "");
    void Delete(T entity);
    // ... removed other method signatures for brevity
}

我的仓库基本实现:

My Repository base implementation:

public abstract class RepositoryBase<D, T> : IRepositoryBase<T>, IDisposable
where T : class
where D : DbContext, new()
{
    private Guid? currUserGuid = null;
    private D dataContext;
    protected D DataContext
    {
        get
        {
            if (dataContext == null)
                dataContext = new D();
            return dataContext;
        }
        set { dataContext = value; }
    }

    public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
    {
        return DataContext.Set<T>().Where(predicate);
    }
    public virtual IQueryable<T> GetAll()
    {
        IQueryable<T> query = DataContext.Set<T>();
        return query;
    }

    public virtual void Delete(T entity)
    {
        OperationStatus stat = TryDelete(entity);
    }
    // .... removed rest for brevity
}

接口和实现混凝土类:

Interface and implementation for concrete class:

    public interface ICustomerRepository : IRepositoryBase<Customer>
{
    Customer GetCustomerAndStatus( Guid custGuid );
}
public class CustomerRepository : RepositoryBase<PCDataEFContext, Customer>, ICustomerRepository
{
    public Customer GetCustomerAndStatus( Guid custGuid )
    {
        return DataContext.Customers.Include( x => x.CustStatusType )
        .SingleOrDefault( x => x.PKGuid == custGuid );
    }
}

我的Ninject依赖解析器:

My Ninject dependency resolver:

    public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;

    public NinjectDependencyResolver()
    {
        kernel = new StandardKernel();
        AddBindings();
    }
    public IKernel Kernel { get { return kernel; } }

    private void AddBindings()
    {
        kernel.Bind<ICustomerRepository>().To<CustomerRepository>();
        // ... other bindings are omitted for brevity
    }
}

最后,这里是我的实体框架生成的DbContext:

and finally, here is my Entity Framework generated DBContext:

public partial class PCDataEFContext : DbContext
{
    public PCDataEFContext()
        : base("name=PCDataEFContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Customer> Customers { get; set; }
}

以上所有code的伟大工程!但正如我在开始时说,我不知道如何注入连接字符串到我在运行时Repositorybase类,这样我不用修改任何我继承了存储库(我有很多他们)。有人请帮助。

All the above code works great! But as I said in the beginning, I don't know how to inject the connection string into my Repositorybase class at runtime so that I don't have to modify any of my inherited repositories (I have plenty of them). Someone please help.

巴布。

推荐答案

你能做到这样吗?

public partial class PCDataEFContext : DbContext
{
    public PCDataEFContext()
        : base(Util.GetTheConnectionString())
    { }
}

public class MyDerivedContext : PCDataEFContext
{
    public MyDerivedContext()
        : base()
    { }
}

class Util
{
    public static string GetTheConnectionString()
    {
        // return the correct name based on some logic...
        return "name=PCDataEFContext";
    }
}

做的另一种方式,可以在您定义的RepositorBase类,通过创建的DbContext后改变ConnectionString的:

Another way of doing it, could be in the RepositorBase class you defined, by altering the connectionstring after the creation of the dbcontext:

    protected D DataContext
    {
        get
        {
            if (dataContext == null)
            {
                dataContext = new D();
                dataContext.Database.Connection.ConnectionString = "the new connectionstring";
            }
            return dataContext;
        }
        set { dataContext = value; }
    }

这篇关于设置的DbContext的连接字符串中使用Ninject我的仓库类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆