Last active
July 4, 2025 07:28
-
-
Save Tragetaschen/0f951b32cea3aaf98c1e9b83953dfcf8 to your computer and use it in GitHub Desktop.
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 Autofac; | |
namespace AutofacFactoryGenerator; | |
public class FactoryTests | |
{ | |
public class Dependency { } | |
public class Startable(Func<Dependency> factory): IStartable | |
{ | |
public void Start() | |
{ | |
Assert.NotNull(factory()); | |
} | |
} | |
private static IContainer BuildContainer() | |
{ | |
var builder = new ContainerBuilder(); | |
builder.RegisterType<Dependency>(); | |
var container = builder.Build(); | |
return container; | |
} | |
[Fact] | |
public void LifetimeWithoutStartable() | |
{ | |
var container = BuildContainer(); | |
using var lifetimeScope1 = container.BeginLifetimeScope(); | |
using var lifetimeScope2 = container.BeginLifetimeScope(); | |
using var lifetimeScope3 = container.BeginLifetimeScope(); | |
var factory1 = lifetimeScope1.Resolve<Func<Dependency>>(); | |
var factory2 = lifetimeScope2.Resolve<Func<Dependency>>(); | |
var factory3 = lifetimeScope2.Resolve<Func<Dependency>>(); | |
var d1 = factory1(); | |
var d2 = factory2(); | |
var d3 = factory3(); | |
Assert.NotSame(d1, d2); | |
Assert.NotSame(d1, d3); | |
Assert.NotSame(d2, d3); | |
} | |
[Fact] | |
public void LifetimeWithStartable() | |
{ | |
var container = BuildContainer(); | |
static void WithStartable(ContainerBuilder c) => c.RegisterType<Startable>().As<IStartable>(); | |
using var lifetimeScope1 = container.BeginLifetimeScope(WithStartable); | |
using var lifetimeScope2 = container.BeginLifetimeScope(WithStartable); | |
using var lifetimeScope3 = container.BeginLifetimeScope(WithStartable); | |
var factory1 = lifetimeScope1.Resolve<Func<Dependency>>(); | |
var factory2 = lifetimeScope2.Resolve<Func<Dependency>>(); | |
var factory3 = lifetimeScope3.Resolve<Func<Dependency>>(); | |
var d1 = factory1(); | |
var d2 = factory2(); | |
var d3 = factory3(); | |
Assert.NotSame(d1, d2); | |
Assert.NotSame(d1, d3); | |
Assert.NotSame(d2, d3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment