I have the followin开发者_运维知识库g 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.
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
var container = builder.Build();
Application["container"] = container;
and access it by
var container = Application["container"] as Container; // assuming Container is the type
精彩评论