Autofac在WebApi和OWIN

时间:2016-03-19 23:45:51

标签: asp.net-web-api2 owin autofac validationattribute

SO上有一些关于允许使用ValidationAttribute(Asp.Net MVC3: Set custom IServiceProvider in ValidationContext so validators can resolve services)进行autofac注入的工作,但我正在使用OWIN和WebApi,所以我不确定这是否可行?

所有其他依赖注入工作正常。

OWIN中没有填充DependencyResolver,我记得在OWIN如何处理验证请求的注入方面有所不同。有谁知道Autofac,OWIN,WebApi和ValidationAttribute是否可行?并且,具体的例子?

1 个答案:

答案 0 :(得分:2)

您需要注册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
        }
    }