1

There's a few posts on SO relating to the work around for allowing autofac injections with ValidationAttribute 's (Asp.Net MVC3: Set custom IServiceProvider in ValidationContext so validators can resolve services) but I'm using OWIN and WebApi so I'm not sure if this is possible?

All other dependency injection is working fine.

DependencyResolver isn't populated in OWIN and I remember reading a difference in how OWIN handles injections for the validation requests. Does anyone know if Autofac, OWIN, WebApi and ValidationAttribute 's are possible? And, with specific examples?

Community
  • 1
  • 1
johnnyboy
  • 869
  • 12
  • 23

1 Answers1

2

You need to register the Autofac middleware and then you need to extend it to the WebApi. Now you can use the Autofac resolution inside the OWIN middleware.

        // Register the Autofac middleware FIRST.
        app.UseAutofacMiddleware(container);

        // extend the autofac scope to the web api
        app.UseAutofacWebApi(HttpConfiguration);

After this, WebApi and OWIN middleware will share the same resolution context, and you can do whatever you want.

For the ValidationAttribute thing you can, for example, do something like this:

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

and then

    public override bool IsValid(object value)
    {
        var dependencyResolver = (AutofacWebApiDependencyResolver)GlobalConfiguration.Configuration.DependencyResolver;
        using (var lifetimeScope= dependencyResolver.BeginScope())
        {
            var foo = lifetimeScope.Resolve<Foo>();

            // use foo
        }
    }
Guillaume Raymond
  • 1,726
  • 1
  • 20
  • 33
Luca Ghersi
  • 3,261
  • 18
  • 32