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

最后都变了- 提交于 2019-12-30 07:16:22

问题


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.

My code is as follows:

my injection:

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

my global.asax

private static HttpContext _context;
public static string GetConnectionStringName() {
  var subDomain = String.Empty;

  if (_context != null) {
    subDomain = _context.Request.Url.SubDomain();
  }

  return String.Format("{0}ConnectionString", subDomain);
}

The problem is the _context (which is set in my Application_BeginRequest) is always null because the WebActivator runs before the application_start.

Is it possible in ninject to specify to call MvcApplication.GetConnectionStringName() when a IUnitOfWork is required rather than on application start?

Is there a better approach to what I'm doing?

Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/7024952/ninject-dynamically-specifying-a-connection-string-based-on-a-sub-domain

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