This project has moved and is read-only. For the latest updates, please go here.

Setting export for import in specific cases.

Oct 12, 2011 at 12:53 PM

This might be a strange case but I want to sometimes reuse the same instance when getting exports with MEF and sometimes create a new.

Basicly I have a WCF service class the is instance per call. Each instance imports a RepositoryFactory which will also be new instance per service class. I return a Repository in the Factory and a repository gets a IDbContext injected.

I want each instance of the Factory to inject the same instance of IDbContext but have seperate instances between Factory instances.


1) Factory1 is created
2) Factory1 creates Repository1-1 that gets IDbContext1 injected
3) Factory1 creates Repository1-2 that gets IDbContext1 injected
4) Factory2 is created
5) Factory2 creates Repository2-1 that gets IDbContext2 injected
6) Factory2 creates Repository2-2 that gets IDbContext2 injected

This should ensures that Repositories created from the same factory share a Unit of Work.

But being new to MEF I'm not sure how I would go about doing that.

This is what I got:

public class RepositoryFactory
    private readonly CompositionContainer _container;

    private readonly IDbContext _context;

    public IRepository<T> CreateRepository<T>() where T : class, IEntity
        //Somehow add the _context instance into the Repository import

        return _container.GetExportedValue<EntityRepository<T>>();

and then

public class EntityRepository<T> : IRepository<T> where T : class, IEntity
    // Perhaps a contract name might help!!
    protected readonly IDbContext _context;
Oct 25, 2011 at 5:51 PM

Hi there-

The design challenge you're facing is commonly addressed using 'nested containers' as a scoping mechanism with MEF.

In essence, you need to create a scope per unit-of-work, and then resolve dependencies from the scope so that all components within a unit of work share the same IDbContext.

It can be quite tricky, so my advice would be to go and search for examples of integrating MEF with WCF this way.

We're aiming to provide more guidance around scoping soon. In the meantime, there's some information that will help you get started on

Hope this helps.