开发者

MEF - Do imports have to be set somehow or could they possibly be null?

开发者 https://www.devze.com 2023-03-23 16:36 出处:网络
Basically I have the f开发者_JAVA百科ollowing: [Import] private IEventAggregator EventAggregator { get; set; }

Basically I have the f开发者_JAVA百科ollowing:

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

  1. Is it ever possible for my app to not have an MEF runtime exception and leave that property as null?
  2. Since the property is private should I bother checking against null in each method? I was thinking, what if one day I decide to NOT use MEF and do something else. I'll still ensure that it can't be null upon instantiation, so do I need to guard against it anyways?
  3. What if it were protected instead, should that give me enough reason to guard against null because now extending classes could set it to null. Or, is that something that I shouldn't worry about (other programmers extending my class and doing stupid things with it).

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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消