开发者

C# Dynamic Dictionary

开发者 https://www.devze.com 2022-12-17 17:43 出处:网络
I would like to find a way to have a Dictionary of various Mock objects with their various instances keyed by some kind of unique identifier. I am using Moq, so the syntax for that is Mock<IFoo>

I would like to find a way to have a Dictionary of various Mock objects with their various instances keyed by some kind of unique identifier. I am using Moq, so the syntax for that is Mock<IFoo> as far as the typing goes. But I would like to have the Dictionary contain basi开发者_如何学Ccally this so I can dynamically resolve and overwrite instances at runtime:

Key = IFoo (basically a type)

Value = new SomeCustomType< T >
{
  T ConcreteObject
  Mock< T > MockObject
}

I may not be getting my question across appropriately but I could use some help!


If you don't need the concrete object you could use an automocking container.

Here's an Autofac automocking container for Moq.


I'm not 100% sure I understand the question, but here's my take. If you want a dictionary of instances keyed by type, the easiest way to do that is to use a static generic class rather than an actual dictionary:

public static class Dict<T> {
    public static T Instance { get; set; }
}

Then, to set the instance associated with type IFoo you would do Dict<IFoo>.Instance = myIFooInstance;, and to get it back out you'd just store the result of Dict<IFoo>.Instance.

If instead, you want to get out Mock instances keyed by types, you could do something very similar:

public static class MockDict<T> {
    public static Mock<T> Instance { get; set; }
}

Then, you can do something along the lines of:

Mock<IFoo> myMock = ...
MockDict<IFoo>.Instance = myMock;
...
Mock<IFoo> myMock2 = MockDict<IFoo>.Instance;
0

精彩评论

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

关注公众号