kenwarner
kenwarner

Reputation: 29120

Resolving imports by namespace with MEF

I'm using MEF as an IoC container.

If the requesting class is in the Foo.UI.* namespace, I want ILogger to resolve to ClientLogger, otherwise it should resolve to Logger. Can I do this?

Upvotes: 2

Views: 388

Answers (2)

Daniel Plaisted
Daniel Plaisted

Reputation: 16744

Thomas's solution using named exports is probably the best you can do with the .NET 4 version of MEF. With next version of MEF, you can probably use a convention via the RegistrationBuilder to change any ILogger imports in the UI namespace to be named imports. IE, effectively doing what Thomas suggested but doing it by convention instead of having to apply it to each of your classes.

A preview of the next version of MEF is available on codeplex.

Upvotes: 1

Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

Maybe with such a workaround, using named exports ?

[Export("clientLogger", typeof(ILogger))]
public class ClientLogger : ILogger {}

[Export("logger", typeof(ILogger))]
public class logger: ILogger {}

And the requesting type in the Foo.UI.* decorate like this

[ImportingConstructor]
public MyService([Import("clientLogger", typeof(ILogger))]ILogger logger)

I know that it's not the best solution but maybe it would work.

Upvotes: 2

Related Questions