I'm using ASP.NET Core. I'm new to Autofac.
A third-party library (NLog) uses my Foo
object for the app's lifetime, so it effectively becomes a singleton, and I can't change that. The problem is Foo
has a scoped dependency, which effectively becomes a singleton too (a captive dependency).
In a related question I was told to change the dependency to Func<Dependency>
so a new instance is created on each request. The builtin container doesn't support Func<>
, so I'm using Autofac.
My type:
public class Foo
{
public Foo(Func<IMyContext> contextFactory) { _contextFactory = contextFactory; }
private readonly Func<IMyContext> _contextFactory;
public void doSomething() { /* shown below */ }
}
My Startup
:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMyContext, MyContext>();
services.AddSingleton<Foo>();
var builder = new ContainerBuilder();
builder.Populate(services);
return new AutofacServiceProvider(builder.Build());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory log)
{
var foo = app.ApplicationServices.GetService<Foo>();
ConfigureNLog(foo); // effectively becomes a singleton, and I can't change that
// ...
}
To test this during a request, I log the instance's hashcode:
public class Foo
{
// ...
public void doSomething()
{
using (var context = _contextFactory())
{
_logger.log(context.GetHashCode()); // should be unique on each request
}
}
}
I expect a unique hashcode on each request, because the dependency is created via a Func<>
factory. But they are always the same! So it's the same instance on each request.
How can I solve this?