Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ImportingConstructor attribute?

Tags:

.net

mef

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?

like image 499
ILovePaperTowels Avatar asked May 31 '12 20:05

ILovePaperTowels


People also ask

What is ImportingConstructor?

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 in c#?

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.


1 Answers

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

  1. Adding a new [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.
  2. Code Contracts are unusable if you have an [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.
  3. Even though your object can logically have fields which are set at initialization time and never reset afterwards, you can't express this with readonly as you would with a normal C# object.
like image 82
JaredPar Avatar answered Sep 22 '22 17:09

JaredPar