2011-03-01 2 views
1

서비스를 가져 오기는 ... 여기에 (내가 중요하지 않은 물건을 생략했다) 내 관련 코드입니다 :PRISM + MEF - 내가 제대로 내 뷰 모델로 서비스를 가져 오는 방법을 알아 내려고 노력하고있어

ClientBootstrapper .cs :

public sealed class ClientBootstrapper : MefBootstrapper 
{ 
    protected override void ConfigureAggregateCatalog() 
    { 
     base.ConfigureAggregateCatalog(); 

     //Add the executing assembly to the catalog. 
     AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); 
    } 

    protected override DependencyObject CreateShell() 
    { 
     return Container.GetExportedValue<ClientShell>(); 
    } 

    protected override void InitializeShell() 
    { 
     base.InitializeShell(); 

     Application.Current.MainWindow = (Window)Shell; 
     Application.Current.MainWindow.Show(); 
    } 
} 

ClientShell.xaml.cs :

[Export()] 
public partial class ClientShell : Window 
{ 
    [Import()] 
    public ClientViewModel ViewModel 
    { 
     get 
     { 
      return DataContext as ClientViewModel; 
     } 
     private set 
     { 
      DataContext = value; 
     } 
    } 

    public ClientShell() 
    { 
     InitializeComponent(); 
    } 
} 

ClientViewModel.cs :

[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 
    } 
} 

RandomService.cs :

[Export()] 
public sealed class RandomService 
{ 
    private static Random _random = new Random(DateTime.Now.Millisecond); 

    public Int32 Next() 
    { 
     return _random.Next(0, 1000); 
    } 
} 


나는 모든 수입 부품 (1) 만족 한 알림을받을 수 있나요,하지만 나는 NullReferenceException이를 얻을 수 (2) return Random.Next();에있는 ClientViewModel. 모든 수입이 만족된다고 말한 후에 왜 NullReferenceException을 얻을지 확신하지 못했습니다.

답변

2

MEF는 정적 속성에 대한 가져 오기를 만족하지 않습니다. 무작위 서비스를 인스턴스 속성으로 만듭니다.

+0

답변으로 받아 들일 것이지만 정적 필드/속성으로 가져 오는 방법이 있는지 알고 싶습니다. – michael

+0

@michael MEF는 당신을 위해 그것을하지 않을 것입니다. MEF는 원하는 동작을 얻지 못할 수도있는 여러 번 생성하고 설정할 수 있기 때문에 정적 백킹 필드 또는 기타 인스턴스를 사용하여 인스턴스 속성을 작성할 수 있습니다. –

0

[ImportingConstructor]을 사용하고 생성자에서 정적 속성을 설정할 수 있습니다.

private static RandomService Random { get; set; } 

[ImportingConstructor] 
public ClientViewModel(RandomService random) 
{ 
    Random = random; 
} 

정적 필드로 설정하지 마십시오.