Simon Fox
Simon Fox

Reputation: 10561

MEF Conditional Import

Is it possible, or where should I look for an extension hook to define a conditional import in MEF?

Sort of the inverse of an optional import (AllowDefault=true). What I have is a property import and I don't want to blow the current value away if it has already been set.

Cheers

Upvotes: 3

Views: 1625

Answers (2)

Daniel Plaisted
Daniel Plaisted

Reputation: 16744

MEF doesn't have support for something like this. You could write a property that ignored any sets after the first non-null one:

private IContract _import;
[Import]
public IContract Import
{
    get { return _import; }
    set
    {
        if (_import == null)
        {
            _import = value;
        }
    }
}

I'm not sure what the use case for this is, so I'm not sure if this will help you. MEF doesn't set imports more than once except for recomposable imports during recomposition.

Upvotes: 1

David Yaw
David Yaw

Reputation: 27864

If you set an import on a set-only property, you can do whatever you want with it.

public class Foo
{
    [Import]
    private object ImportData { set { if(this.Data == null) this.Data = value } }

    public object Data { get; set; }
}

Upvotes: 4

Related Questions