如何在设计时在多个程序集上使用单例
我有 3 个程序集:
- MyApp.Views (使用 MyApp.Data 和 MyApp.Metadata)
- MyApp.Data (使用 MyApp.Metadata)
- MyApp.Metadata
我有一个接口,比如 IMetadata。然后,我在 MyApp.Metadata 中也有一个实现,我将其注册在单例类中:
IoCContainer.Instance.Register<IMetadata, Metadata>();
然后,在设计时,我使用需要使用元数据的程序集(但它是解析类型的 MyApp.Data):
IoCContainer.Instance.ResolveType<IMetadata>();
但是这个失败了。 IoCContainer.Instance 不包含相同的接口(实际上,它是空的)。单例实现非常基本:
public class IoCContainer
{
static IoCContainer()
{
Instance = new IoCContainer();
}
public static IoCContainer Instance { get; private set; }
}
不知何故,看起来单独的程序集被加载到单独的应用程序域(或类似的东西)中。有人知道这个问题的解决方案吗?
I have 3 assemblies:
- MyApp.Views (uses MyApp.Data and MyApp.Metadata)
- MyApp.Data (uses MyApp.Metadata)
- MyApp.Metadata
I have an interface, say IMetadata. Then, I also have an implementation in MyApp.Metadata which I register in a singleton class:
IoCContainer.Instance.Register<IMetadata, Metadata>();
Then, in design time, I use an assembly that needs to use the metadata (but it's the MyApp.Data that resolves the type):
IoCContainer.Instance.ResolveType<IMetadata>();
But this fails. The IoCContainer.Instance does not contain the same interfaces (actually, it's empty). The singleton implementation is really basic:
public class IoCContainer
{
static IoCContainer()
{
Instance = new IoCContainer();
}
public static IoCContainer Instance { get; private set; }
}
Somehow, it looks like separate assemblies are loaded in separate app domains (or something like that). Anyone knows a solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是线程问题。您的单例实例可以由不同的线程实例化两次。看看 http://www.yoda.arachsys.com/csharp/singleton.html 。它更详细地解释了它并为您提供了线程安全的解决方案。
Could be a threading issue. Your singleton instance could be instantiated twice by different threads. Have a look at http://www.yoda.arachsys.com/csharp/singleton.html. It explains it in more detail and provides you with a thread safe solution.
好吧,问题似乎已经解决了。可能有两个原因:
第一,有时 Visual Studio 会“更新”对共享库的引用,因此一个指向 bin\debug\myshared assembly.dll,另一个仍然指向 ....\lib\myshared assembly。这是 VS2010 的某种愚蠢行为,它试图超越开发人员。
其次,我对 IoC 容器进行了这样的定义:
我将其更改为:
无论如何,问题已解决:)
Ok, problem seems to be solved. It might have 2 causes:
First, sometimes visual studio "updates" your references to shared libraries so one points to the bin\debug\mysharedassembly.dll, and the other one still points to ....\lib\mysharedassembly. This is some kind of stupid behavior of VS2010 where it tries to outthink the developer.
Second, I had this definition of the IoC Container:
Which I changed to:
Anyway, problem solved :)