Ninject - dynamically specifying a connection string based on a sub domain

后端 未结 1 1697
小鲜肉
小鲜肉 2021-01-06 13:17

I\'m trying to specify a connection string dynamically based of the url using ninject.

I\'m using the ninject.mvc nuget package that uses the webActivator.

相关标签:
1条回答
  • 2021-01-06 13:56

    You should use the Ninject binding like this.

    kernel.Bind<IUnitOfWork>().To<UnitOfWork>()
      .WithConstructorArgument("connectionString", context => MvcApplication.GetConnectionStringName());
    

    Note that context here is of type Ninject's IContext and so has nothing to do with HttpContext.

    Anyway I think you approach is suitable for this.

    Sometimes (especially when there are multiple related parameters to be injected) I prefer creating an interface and specific implementations for the configurations and let them injected by standard bindings like this.

    public interface IUnitOfWorkConfiguration {
        string ConnectionString { get; }
    }
    
    public class AppConfigUnitOfWorkConfiguration : IUnitOfWorkConfiguration {
        public string ConnectionString { get { ... } }
    }
    
    public class UnitOfWork {
        public UnitOfWork(IUnitOfWorkConfiguration configuration) {
        }
    }
    
    Bind<IUnitOfWorkConfiguration>().To<AppConfigUnitOfWorkConfiguration>();
    

    Using this approach you can avoid specifying parameter names as string literals.

    One more note about using HttpContext. I do not recommend using it that way because of thread safety issues. You should either mark your private static field _context with the [ThreadStatic] atribute or as a better choice simply use HttpContext.Current everywhere.

    0 讨论(0)
提交回复
热议问题