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

怎甘沉沦 提交于 2019-11-30 23:49:27

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!