Created
October 31, 2019 14:09
-
-
Save seesharper/f151ababad02f5af59185aaffae77e07 to your computer and use it in GitHub Desktop.
Testbase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection; | |
using DbReader.LightInject; | |
namespace DbReader.Tests | |
{ | |
public class ContainerFixture : IDisposable | |
{ | |
public ContainerFixture() | |
{ | |
var container = CreateContainer(); | |
Configure(container); | |
container.RegisterFrom<CompositionRoot>(); | |
ServiceFactory = container.BeginScope(); | |
InjectPrivateFields(); | |
} | |
private void InjectPrivateFields() | |
{ | |
var privateInstanceFields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); | |
foreach (var privateInstanceField in privateInstanceFields) | |
{ | |
privateInstanceField.SetValue(this, GetInstance(ServiceFactory, privateInstanceField)); | |
} | |
} | |
internal Scope ServiceFactory { get; } | |
public void Dispose() => ServiceFactory.Dispose(); | |
public TService GetInstance<TService>(string name = "") | |
=> ServiceFactory.GetInstance<TService>(name); | |
private object GetInstance(IServiceFactory factory, FieldInfo field) | |
=> ServiceFactory.TryGetInstance(field.FieldType) ?? ServiceFactory.GetInstance(field.FieldType, field.Name); | |
internal virtual IServiceContainer CreateContainer() => new ServiceContainer(); | |
internal virtual void Configure(IServiceRegistry serviceRegistry) {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment