您需要注册 Autofac 中间件,然后您需要将其扩展至 WebApi。现在您可以在 OWIN 中间件中使用 Autofac 分辨率。
// Register the Autofac middleware FIRST.
app.UseAutofacMiddleware(container);
// extend the autofac scope to the web api
app.UseAutofacWebApi(HttpConfiguration);
此后,WebApi 和 OWIN 中间件将共享相同的解析上下文,您可以为所欲为。
例如,对于 ValidationAttribute 事情,您可以执行以下操作:
public class AppStartup
{
public void Configuration(IAppBuilder app)
{
// Get your HttpConfiguration. In OWIN, you'll create one
// rather than using GlobalConfiguration.
var config = new HttpConfiguration();
//Set builder
var builder = new ContainerBuilder();
//IoC container build
var container = builder.Build();
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(HttpConfiguration);
WebApiConfig.Register(HttpConfiguration);
app.UseWebApi(HttpConfiguration);
}
}
接着
public override bool IsValid(object value)
{
var dependencyResolver = (AutofacWebApiDependencyResolver)GlobalConfiguration.Configuration.DependencyResolver;
using (var lifetimeScope= dependencyResolver.BeginScope())
{
var foo = lifetimeScope.Resolve<Foo>();
// use foo
}
}