tags:

views:

18

answers:

1

Is there any way I can compose (or get an exported value) with a specific instance as one of it's dependencies?

I have something like this:

public interface IEntityContext
{
    IEntitySet<T> GetEntitySet<T>();
}
[Export(typeof(IEntitySet<MyEntity>))]
class MyEntitySet
{
    public MyEntitySet(IEntityContext context)
    {
    }
}
// then through code
var container = ...;
using (var context = container.GetExportedValue<IEntityContext>())
{
    var myEntitySet = context.GetEntitySet<MyEntity>();
    // I wan't myEntitySet to have the above context constructor injected
}

I'm trying to mock something like entity framework for testability sake. Not sure though if I would want to go down this road. Anyway, should I be creating a new container for this very purpose. A container specific to the mocking of this one IEntityContext object.

+1  A: 

So, if my understanding is correct, you want to be able to inject whatever IEntityContext is available to your instance of MyEntitySet?

[Export(typeof(IEntitySet<MyEntity>))]
public class MyEntitySet : IEntitySet<MyEntity>
{
    [ImportingConstructor]
    public MyEntitySet(IEntityContext context)
    {

    }
}

Given that you then want to mock the IEntityContext? If so, you could then do this:

var contextMock = new Mock<IEntityContext>();
var setMock = new Mock<IEntitySet<MyEntity>>();

contextMock
    .Setup(m => m.GetEntitySet<MyEntity>())
    .Returns(setMock.Object);

Container.ComposeExportedValue<IEntityContext>(contextMock.Object);

var context = Container.GetExportedValue<IEntityContext>();
var entitySet = context.GetEntitySet<MyEntity>();

(That's using Moq)

You can use your existing CompositionContainer infrastructure by adding an exported value.

Does that help at all? Sorry it doesn't seem exactly clear what you are trying to do...

Matthew Abbott
I need to experiment a bit with this. And you are right in that I want to be able to inject a speicfic IEntityContext to any instance of IEntitySet that is created by the Container. I haven't tried `ComposeExportedValue` yet.
John Leidegren