Created
January 12, 2017 18:13
-
-
Save pizycki/e59810518beb5a05a490cf8600032854 to your computer and use it in GitHub Desktop.
Autofac registration xUnit tests
This file contains 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
public class AutofacRegistration_Tests | |
{ | |
[Fact] | |
public void any_type_in_service_layer_should_NOT_be_registered_as_InstancePerRequest() | |
{ | |
var containerRegistrations = GetContainer().ComponentRegistry.Registrations; | |
var results = containerRegistrations.ToDictionary(reg => reg, IsRegistrationScopeInstancePerRequest); | |
/* When test fails, debug this test and run following command in `Immediate console`: | |
* var invalid = results.Where(r=>r.Value); | |
* Then look into your `Local variables` window for new variable named "invalid". | |
* It contains all invalid registrations. | |
*/ | |
#if DEBUG | |
foreach (var registration in results.Where(result => result.Value).Select(result => result.Key)) | |
{ | |
Debug.WriteLine($"Type {registration.Activator} is registered with invalid scope."); | |
} | |
#endif | |
results | |
.Where(result => result.Value) | |
.Select(result => result.Key) | |
.ShouldBeEmpty(); | |
} | |
private static bool IsRegistrationScopeInstancePerRequest(IComponentRegistration registration) | |
{ | |
if (registration.Lifetime.GetType() != typeof(MatchingScopeLifetime)) | |
return false; | |
// ReSharper disable once PossibleNullReferenceException | |
var tags = typeof(MatchingScopeLifetime) | |
.GetField("_tagsToMatch", BindingFlags.NonPublic | BindingFlags.Instance) | |
.GetValue(registration.Lifetime) as object[]; | |
return tags != null && tags.Any(tag => tag == MatchingScopeLifetimeTags.RequestLifetimeScopeTag); | |
} | |
private IContainer GetContainer() | |
{ | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment