Reputation: 15282
Basically I have the following:
[Import]
private IEventAggregator EventAggregator { get; set; }
public void DoSomething()
{
//Should I bother to check for null here before using EventAggregator?
}
A couple of things here first:
Question 2 is moreover regarding the question of: Should we check against null even if the property we are checking against is maintained within the class (i.e. We should guard the state of our class to not allow that scenario).
Upvotes: 2
Views: 966
Reputation: 61589
The default behaviour with MEF is to throw an exception when the definitions cannot be created due to missing parts. You can address this, by changing your [Import]
attribute to [Import(AllowDefault = true)]
, which will allow for null values when there are missing exports. This will obviously impact your code, as you will need to explicitly check for null
in your DoSomething
method.
In regards to the access visibility, defining your import property as private
means that it cannot be altered externally so to this end...can you guarantee that this property will be set properly? If not, you need to check for null
.
Upvotes: 6