问题
I have an ASP.NET application and a Windows Service. I am using Unity as the IoC container. I placed the Composition Root in a seperate class library, because both applications are supposed to use the same DI container.
DI bootstrapper:
namespace CompositionRoot {
public static class DiBootstrapper {
private static IUnityContainer _container;
public static IUnityContainer Initialize() {
return _container ?? (_container = BuildUnityContainer());
}
private static IUnityContainer BuildUnityContainer() {
var container = new UnityContainer();
container.AddNewExtension<ContainerExtension>();
return container;
}
}
public class ContainerExtension: UnityContainerExtension {
protected override void Initialize() {
var connectionString = ConfigurationManager.ConnectionStrings["KSecureEntities"].ConnectionString;
var sqlCtorParam = new InjectionConstructor(connectionString);
this.Container.RegisterType < Acquaintance.RSS.IRssRepository, RssRepository > (new ContainerControlledLifetimeManager());
this.Container.RegisterType < IRssFeedRepository, RssFeedRepository > (new TransientLifetimeManager(), sqlCtorParam);
this.Container.RegisterType<IRssTicker, RssTicker>(new ContainerControlledLifetimeManager());
this.Container.RegisterType < RssTickerHub > (new InjectionFactory(RssTickerHub));
....
}
private static object RssTickerHub(IUnityContainer p) {
var rssRepository = p.Resolve < IRssFeedRepository > ();
var rssTicker = p.Resolve < IRssTicker > ();
var rssTickerHub = new RssTickerHub(rssRepository, rssTicker);
return rssTickerHub;
}
}
}
The first project to run Initialize() on the DiBootstrapper is the Windows Service. When the method is run, the _container variable is set.
Afterwards the ASP.NET application runs Initialize() from Application_Start(), but this time the variable is null, and the container gets instantiated again.
How can I share the same container across both projects?
回答1:
You cannot.
It does not work that way. You have two different processes, the Windows Service and the process your webserver spuns up when your ASP.NET is called. They both load the library assembly, but each loads his own copy into memory. That's how processes work with libraries.
There is no easy solution. You cannot share objects that way. You will need to find another solution. If you don't have singleton lifetimes in your DI container, just having the same configuration for both processes should be enough. if you want to share objects between processes, you might be best served by asking a new question on how to do that in a specific situation because there are many ways to achieve a goal without doing it, but we need to know your goal to give such an answer.
来源:https://stackoverflow.com/questions/37906216/accessing-a-static-variable-from-different-assemblies