访问在 Application_Start ASP.NET MVC 3 中创建的变量
我的 Application_Start 方法中运行以下代码:
var builder = new ContainerBuilder();
var store = new DocumentStore { Url = "http://localhost:8081" };
store.Initialize();
builder.RegisterInstance(store);
var container = builder.Build();
我正在使用 AutoFac 来存储 RavenDB DocumentStore 的实例。现在我知道这只在应用程序启动时运行一次,但是我如何能够访问容器变量,以便我可以从应用程序中的任何位置检索存储在其中的 DocumentStore。
I have the following code running in my Application_Start method:
var builder = new ContainerBuilder();
var store = new DocumentStore { Url = "http://localhost:8081" };
store.Initialize();
builder.RegisterInstance(store);
var container = builder.Build();
I am using AutoFac to store the instance of my RavenDB DocumentStore. Now I know this only runs once when the application is started however how would I be able to access the container variable so that I can retrieve the DocumentStore that in stored in there from anywhere in my application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DI 的想法是,您在
Application_Start
中配置容器,并将所有必要的依赖项连接到对象中,以便您永远不需要在代码的其他部分访问容器。因此,回答您的问题:只需让应用程序中需要访问 DocumentStore 的部分将其作为构造函数参数,然后配置 AutoFac 来注入它。让代码的其他部分依赖于容器是一种不好的做法,因为它们与容器紧密耦合。
The idea of DI is that you configure your container in the
Application_Start
and you wire all the necessary dependencies into your objects so that you never need to access the container in other parts of your code. So to answer your question: simply have the parts of your application that need to access the DocumentStore take it as constructor argument and then configure AutoFac to inject it.Having other parts of your code depending on the container is a bad practice as they become tightly coupled to it.
好的!正如达林指出的那样,这不是一个好的做法,但如果你愿意的话,
你可以
通过以下方式访问它
Ok! As Darin pointed out, it's not a good practice but if you want to,
you could do
and access it by