using System; using System.Collections.Generic; using Moq; using Ninject.Activation; using Ninject.Injection; namespace Ninject.Moq { /// /// Creates mocked instances via Moq. /// public class MockProvider : IProvider { private static readonly Dictionary _injectors = new Dictionary(); /// /// Initializes a new instance of the class. /// /// The injector factory component. public MockProvider(IInjectorFactory injectorFactory) { InjectorFactory = injectorFactory; } /// /// Gets the injector factory component. /// public IInjectorFactory InjectorFactory { get; private set; } #region IProvider Members /// /// Gets the type (or prototype) of instances the provider creates. /// public Type Type { get { return typeof (Mock<>); } } /// /// Creates an instance within the specified context. /// /// The context. /// The created instance. public object Create(IContext context) { ConstructorInjector injector = GetInjector(context.Request.Service); var mock = injector.Invoke() as Mock; return mock.Object; } #endregion private ConstructorInjector GetInjector(Type service) { lock (_injectors) { Type mockType = typeof (Mock<>).MakeGenericType(service); if (_injectors.ContainsKey(mockType)) return _injectors[mockType]; ConstructorInjector injector = InjectorFactory.Create(mockType.GetConstructor(Type.EmptyTypes)); _injectors[mockType] = injector; return injector; } } /// /// Gets a callback that creates an instance of the . /// /// The created callback. public static Func GetCreationCallback() { return ctx => new MockProvider(ctx.Kernel.Components.Get()); } } }