对于我的 ASP.NET Web API 项目,我有以下设置,它使用 Autofac 作为 IoC 容器:
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();
}
我有以下消息处理程序,它检索ConfContext
实例只是为了好玩:
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);
}
}
由于将在构造控制器之前调用我的消息处理程序,因此我应该在ConfContext
控制器上获得相同的实例。但是,如果我尝试检索ConfContext
asFunc<Owned<ConfContext>>
但我得到的是相同的实例,我想获得单独的实例。如果我删除InstancePerApiRequest
注册,在我只想按ConfContext
原样检索的情况下,我将失去 Per API 请求支持。
有什么方法可以支持这两种情况吗?
编辑