2016-03-19 47 views
1

在SO上有幾篇關於允許使用ValidationAttribute(Asp.Net MVC3: Set custom IServiceProvider in ValidationContext so validators can resolve services)自動注入的解決方法的文章,但我使用OWIN和WebApi,所以我不確定這是否是可能?Autofac注入到WebApi和OWIN上的ValidationAttribute

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

DependencyResolver未在OWIN中填充,我記得閱讀OWIN如何處理注入驗證請求的區別。有誰知道Autofac,OWIN,WebApi和ValidationAttribute是否可能?並且,具體的例子?

回答

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 
     } 
    }