访问在 Application_Start ASP.NET MVC 3 中创建的变量

发布于 2024-10-25 00:01:44 字数 382 浏览 3 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紅太極 2024-11-01 00:01:44

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.

忘羡 2024-11-01 00:01:44

好的!正如达林指出的那样,这不是一个好的做法,但如果你愿意的话,
你可以

var container = builder.Build();
Application["container"] = container;

通过以下方式访问它

var container =  Application["container"] as Container; // assuming Container is the type

Ok! As Darin pointed out, it's not a good practice but if you want to,
you could do

var container = builder.Build();
Application["container"] = container;

and access it by

var container =  Application["container"] as Container; // assuming Container is the type
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文