namespace StackOverflow42744319
public static void Main(string[] args)
var builder = new ContainerBuilder();
builder.RegisterType<MyContext>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<DbContextFactory<MyContext>>().As<IDbContextFactory<IContext>>();
builder.RegisterType<Foo>().AsSelf();
var container = builder.Build();
var instance1 = container.Resolve<Foo>();
var instance2 = container.Resolve<Foo>();
public interface IContext
public class MyContext : IContext
public Guid Guid { get; private set; }
private readonly IDbContextFactory<IContext> _contextFactory;
public Foo(IDbContextFactory<IContext> contextFactory)
_contextFactory = contextFactory;
var context = _contextFactory.Create();
Console.WriteLine(context.Guid);
Console.WriteLine(context.GetHashCode());
public interface IDbContextFactory<out TContext>
where TContext : IContext
public class DbContextFactory<TContext> : IDbContextFactory<TContext>
where TContext : IContext
private readonly Func<TContext> _contextCreator;
public DbContextFactory(Func<TContext> contextCreator)
_contextCreator = contextCreator;
return _contextCreator();