For my ASP.NET Web API project, I have the following set up which uses Autofac as the IoC container:
protected void Application_Start(object sender, EventArgs e)
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.DependencyResolver =
new AutofacWebApiDependencyResolver(
RegisterServices(new ContainerBuilder()));
config.Routes.MapHttpRoute("DefaultRoute", "api/{controller}");
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<ConfContext>().InstancePerApiRequest();
return builder.Build();
}
And I have the following message handler which retrieves the ConfContext
instance just for fun:
public class MyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
ConfContext ctx = (ConfContext)request.GetDependencyScope().GetService(typeof(ConfContext));
return base.SendAsync(request, cancellationToken);
}
}
As my message handler will be called before the controller is constructed, I should get the same ConfContext
instance at the controller. However, I want to get separate instances if I try to retrieve a ConfContext
as Func<Owned<ConfContext>>
but I am getting the same instance. If I remove the InstancePerApiRequest
registration, I will lose the Per API request support on cases where I want to just retrieve the ConfContext
as it is.
Is there any way to support both cases here?
Edit
Sample application is here: https://github.com/tugberkugurlu/EntityFrameworkSamples/tree/master/EFConcurrentAsyncSample/EFConcurrentAsyncSample.Api