Skip to content

Instantly share code, notes, and snippets.

@pizycki
Created January 12, 2017 18:13
Show Gist options
  • Save pizycki/e59810518beb5a05a490cf8600032854 to your computer and use it in GitHub Desktop.
Save pizycki/e59810518beb5a05a490cf8600032854 to your computer and use it in GitHub Desktop.
Autofac registration xUnit tests
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