c# - Difference between Import and ImportingConstructor attributes in MEF with proper examples? -
can me import , importingconstructor attributes in mef relevant examples , when use ? use of [import(allowdefault = true)] ?
from understanding of mef:
export attribute defined on class of type t t interface , create instance of class import attribute should defined on reference variable below
[export(typeof(icalculator))] class mysimplecalculator : icalculator { // implement interface } class mymainclass { // mef engine creates instance export attribute defined // on mysimplecalculator [import(typeof(icalculator))] public icalculator calculator; }
if multiple exports of type t defined in given assembly can use importmany attribute.
so can explain when use import , importingconstructor , allowdefault attribute in constructor ?
it great if can explain better examples.
any appreciated. thanks
importingconstructor
the way import/export parts in sample code, if mymainclass
getting composed, implicit parameterless constructor called, then instance of mysimplecalculator
assigned calculator
field.
now let's rather want have readonly field/a get-only property, or otherwise need access icalculator
in constructor, need have passed constructor rather later on assigned field:
public interface icalculator { bool quack { get; } } [export(typeof(icalculator))] public class mysimplecalculator : icalculator { public bool quack => true; } [export] public class mymainclass { public icalculator calculator { get; } public string blah { get; } [importingconstructor] public mymainclass(icalculator calculator) { calculator = calculator; // assign readonly property blah = calculator.quack ? "foo" : "bar"; // based on calculator } }
now argument(s) constructor implicitly imported , satisfied corresponding export.
allowdefault
if [import] something, must available or composition fails.
if [import(allowdefault = true)] something, composition wont' fail if there's no corresponding export, null/false/0 imported value.
btw: sorry being sarcastic, answer rtfm.
Comments
Post a Comment