C# 棱镜&x2B;MEF—导入服务
我正在试图找出如何将服务正确导入到我的ViewModel中。。。以下是我的相关代码(我省略了不重要的内容): ClientBootstrapper.cs: ClientViewModel.cs: RandomService.cs:C# 棱镜&x2B;MEF—导入服务,c#,dependency-injection,service,mef,prism-4,C#,Dependency Injection,Service,Mef,Prism 4,我正在试图找出如何将服务正确导入到我的ViewModel中。。。以下是我的相关代码(我省略了不重要的内容): ClientBootstrapper.cs: ClientViewModel.cs: RandomService.cs: 我确实收到了所有导入部分都已满足的通知(1),但随后我在return Random.Next()上收到了一个NullReferenceException(2)在ClientViewModel内部。我不知道为什么在我被告知所有导入都已满足后会得到NullReferen
我确实收到了所有导入部分都已满足的通知(1),但随后我在
return Random.Next()上收到了一个NullReferenceException(2)代码>在ClientViewModel内部。我不知道为什么在我被告知所有导入都已满足后会得到NullReferenceException…MEF不会满足静态属性上的导入。将随机服务设置为实例属性。您可以使用[ImportingConstructor]
并在构造函数中设置静态属性
private static RandomService Random { get; set; }
[ImportingConstructor]
public ClientViewModel(RandomService random)
{
Random = random;
}
只是不要将其设置为静态字段。我接受这个答案,但仍然希望知道是否有方法将导入到静态字段/属性。@michael MEF不会为您这样做。您可以编写带有静态支持字段或其他内容的实例属性,尽管因为MEF可以多次创建和设置它,这可能无法获得您想要的行为。
[Export()]
public partial class ClientShell : Window
{
[Import()]
public ClientViewModel ViewModel
{
get
{
return DataContext as ClientViewModel;
}
private set
{
DataContext = value;
}
}
public ClientShell()
{
InitializeComponent();
}
}
[Export()]
public class ClientViewModel : NotificationObject, IPartImportsSatisfiedNotification
{
[Import()]
private static RandomService Random { get; set; }
public Int32 RandomNumber
{
get { return Random.Next(); } //(2) Then this throws a Null Exception!
}
public void OnImportsSatisfied()
{
Console.WriteLine("{0}: IMPORTS SATISFIED", this.ToString()); //(1)This shows up
}
}
[Export()]
public sealed class RandomService
{
private static Random _random = new Random(DateTime.Now.Millisecond);
public Int32 Next()
{
return _random.Next(0, 1000);
}
}
private static RandomService Random { get; set; }
[ImportingConstructor]
public ClientViewModel(RandomService random)
{
Random = random;
}