我有一个叫做NotificationScheduler的单例类。我真的只可能在我的应用程序中有这些。单件模式是通过“实例”属性实现,只能通过这个属性这样访问实例:在XAML中使用单例 - 可能吗?
private static NotificationScheduler _instance = null;
public static NotificationScheduler Instance
{
get { return _instance ?? (_instance = new NotificationScheduler()); }
}
public NotificationScheduler()
{
#if DEBUG
if (_instance != null)
Debug.WriteLine(
"WARN: A second Instance of NotificationScheduler has been created");
#endif
_instance = this;
init();
}
但我也有一个原因要在XAML中创建这样的:
<NotifyIcon:NotificationScheduler x:Key="NotificationScheudlerInstance"
IconSource="/Images\Icons/myicon.ico"
我知道这不使用实例属性!这甚至可能吗?如果我访问实例在这样的代码,一个实例被创建过程中的两次:
NotificationScheduler.Instance.DoSomething();
NotificationScheduler n = (NotificationScheduler) FindResource("NotifyIcon");
n.DoSomething();
此刻,我的解决办法是做FindResource事情通过XAML代码来创建实例,然后一切正常精细。
问题:我可以通过访问静态属性在XAML中创建资源吗?
每当我听到单身人士,我去这里:http://csharpindepth.com/articles/general/singleton.aspx – Rudi
除了下面关于.NET 4.5和静态的答案。一种可能性是管理工厂或IOC库中支持单例的类接口之外的单例。 – kenny
@Rudi是的,这是我们给受访者阅读的一些代码来自的帖子。但它与这个问题无关;-) – Akku