开发者

Compose part with specific instance

开发者 https://www.devze.com 2023-01-07 09:26 出处:网络
Is there any way I can compose (or get an exported value) with a specific instance as one of it\'s dependencies?

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 sur开发者_JAVA技巧e 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.


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消