Search code examples
c#.netmefautofac

Exporting decorated Autofac component to MEF


I am using Autofac as the IoC container in a project. I am loading "plugins" into my container through MEF using the Autofac Mef integration library. All working well.

I am also using the decorator pattern on a couple of services, which causes me headache. This is how I register one of them:

builder.RegisterDecorator<IAuthorizationHandler>((context, handler) =>
                context.Resolve<CachedAuthManager>(new Parameter[] { new NamedParameter("manager", handler) }), "authhandler", "authcached");

Now I wish to export one of these to MEF. I cannot apply the extension method "Exports" in the example above to the builder, as I usually do on the container builder, like this example:

builder.RegisterType<LogHandler>().As<ILogHandler>).Exported(x => x.As<ILogHandler>());

How do I properly and cleanly tell Autofac that my registered, decorated component is to be exported to MEF?

Thanks for helping out


Solution

  • I think you've found one of the areas where the MEF-Autofac abstraction analogy currently breaks down.

    MEF works pretty heavily on named contracts, which is to say (basically) known mappings of types to interfaces. You can see this in the way export definitions are actually defined - with a named contract and some metadata. You also see it in the way part catalogs work - import and export definitions, catalogs that really support only types (assembly scanning, specified types, etc.). It really wants to map an interface to a type... so it can further map those types to named contracts and satisfy dependency chains down the stack.

    Autofac allows more dynamic functionality with lambdas, decorators, and registration sources. The actual type backing an interface can change based on the execution of a lambda; and the decorator is an example of that.

    The Autofac/MEF bridge stuff does its best to fake things out and get exports lined up with imports using named services and registration events internally... but it doesn't support doing that for dynamic registrations like decorators (which are actually pretty complex on the back end and uses registration sources to get its job done).

    It would take more than a couple of lines of code changes to the Autofac internals to get this to work... which is to say, sorry, but you're currently out of luck.

    If it's an important thing for you, you might want to file an issue and/or submit a pull request.