I'm trying to understand when [ImportingConstructor]
would be more appropriate than decorating properties with [import]
. Is it a personal preference, or something that allows classes to be constructed by other DI containers or are there benfits over [import]
?
I'd think that maybe if you didn't want to expose public properties but MEF will resolve private fields too, so again, where is the benefit?
By using [ImportingConstructor] , you allow one class that serves as an export to import its dependencies. This dramatically simplifies the architecture, as you can decouple the dependencies of a concrete object from its implementation.
What is MEF? The Managed Extensibility Framework or MEF is a library for creating lightweight, and extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies.
The problem with using [Import]
is that it separates the creation of an object into two distinct and observable phases: created and initialized. Where [ImportingConstructor]
allows this to remain as a single phase exactly as it would for every other .Net object.
This difference becomes observable in a number of ways
[Import]
on a field changes the logical contract of a type. Yet it doesn't change the public or usage contract. This means any code which previously compiled will continue to compile even though the objects dependencies have changed (think unit tests). This takes what should be a compile time error and makes it a runtime one.[Import]
. The contract verification engine properly recognizes that all fields can exist as null
values and will require a check before every use of a field. readonly
as you would with a normal C# object.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With