Radarr/NzbDrone.Core.Test/Ninject.Moq/MockProvider.cs

80 lines
2.5 KiB
C#
Raw Normal View History

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