Ninject - 基于子域动态指定连接字符串
我正在尝试使用 ninject 根据 url 动态指定连接字符串。
我正在使用 ninject.mvc nuget 包,该包使用 webActivator。
我的代码如下:
我的注入:
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);
}
问题是 _context (在我的 Application_BeginRequest 中设置)始终为 null,因为 WebActivator 在 application_start 之前运行。
ninject 是否可以指定在需要 IUnitOfWork
时而不是在应用程序启动时调用 MvcApplication.GetConnectionStringName()
?
对于我正在做的事情有更好的方法吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该像这样使用 Ninject 绑定。
请注意,这里的
context
是 Ninject 的IContext
类型,因此与HttpContext
无关。无论如何,我认为你的方法适合这个。
有时(特别是当要注入多个相关参数时)我更喜欢为配置创建一个接口和特定实现,并让它们通过像这样的标准绑定注入。
使用这种方法,您可以避免将参数名称指定为字符串文字。
关于使用
HttpContext
的更多注意事项。由于线程安全问题,我不建议以这种方式使用它。您应该使用[ThreadStatic]
属性标记您的私有静态字段_context
,或者作为更好的选择,只需在各处使用HttpContext.Current
即可。You should use the Ninject binding like this.
Note that
context
here is of type Ninject'sIContext
and so has nothing to do withHttpContext
.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.
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 useHttpContext.Current
everywhere.