使用Autofac的ASP.Net MVC构造函数注入 - 更改运行时ConnectionString

时间:2017-04-10 10:37:09

标签: asp.net asp.net-mvc dependency-injection autofac

需要一些帮助,尝试根据参数解决问题更改连接字符串运行时。我正在使用AutoFac依赖注入。用户将登录并从数据库中检索连接字符串,并根据连接字符串连接到相应的服务器和数据库。当我传递硬编码连接字符串时,它工作正常,但我需要传递动态连接字符串以下是用于注册的代码

 private static AutofacDependencyResolver SetAutofacContainer(ContainerBuilder builder)
    {

        builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();
        builder.RegisterType<UnitOfWork>().As<Interface.Uow.IUnitOfWork>().InstancePerRequest();


      //  builder.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(), new InjectionConstructor(connectionString));

        ////Repository
        builder.RegisterType<VoucherRepository>().As<Interface.Repository.IVoucherRepository>().InstancePerRequest();
        builder.RegisterType<CustomerRepository>().As<Interface.Repository.ICustomerRepository>().InstancePerRequest();
        builder.RegisterType<UserRepository>().As<Interface.Repository.IUserRepository>().InstancePerRequest();

        ////services
        builder.RegisterType<VoucherBusinessService>().As<IVoucherBusinessService>().InstancePerRequest().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
        builder.RegisterType<CustomerBusinessService>().As<ICustomerBusinessService>().InstancePerRequest().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
        builder.RegisterType<UserBusinessService>().As<IUserBusinessService>().InstancePerRequest().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

        builder.RegisterType<DbFactory>().As<IDbFactory>().WithParameter("ConnectionString", "Data Source=TESTSERVER;Initial Catalog=TradingManagerClient;Integrated Security=True");

        Autofac.IContainer container = builder.Build();
        //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        return new AutofacDependencyResolver(container);
} 

以下是我的DBFactory类

      public class DbFactory : Disposable, IDbFactory
{
    private CoreDbContext _coreDbContext = null;

    public DbFactory() 
    {
        //For CodeFirst It is required
        //Database.SetInitializer<CoreDbContext>(null);
    }

    private string conn;
    public DbFactory(string ConnectionString)
    {
        //For CodeFirst It is required
        //Database.SetInitializer<CoreDbContext>(null);
        this.conn = ConnectionString;
    }

    public CoreDbContext GetDbContext
    {
        get
        {
            return this._coreDbContext ?? (this._coreDbContext = new CoreDbContext(conn));
        }
    }

    protected override void DisposeCore()
    {
        if (this._coreDbContext != null)
            this._coreDbContext.Dispose();
    }

    /// <summary>
    /// Gets the CoreDbContext
    /// </summary>
    public ICoreDbContext Get
    {
        get {  return GetDbContext; }
    }
}

我想在运行时将连接字符串传递给我的DBFactory类。我是否需要在控制器级别处理它,如果是,那么如何? 请在这方面提供指导。

0 个答案:

没有答案