使用带有OWIN和WebAPI 2.1的AutofacWebApiDependencyResolver时出现问题

时间:2014-07-30 21:24:17

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

我似乎无法在OAuthAuthorizationServerProvider中使用DependencyResolver。

DependencyResolver.Current

返回我不使用的MVC和

GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IXXX))

引发以下错误:

  

从请求实例的作用域中看不到具有匹配'AutofacWebRequest'的标记的作用域。这通常表示SingleInstance()组件(或类似场景)正在请求注册为每HTTP请求的组件。在Web集成下,始终从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,从不从容器本身请求

任何想法,如果我做错了什么或者我根本无法使用我正在尝试的依赖?

这就是我的Startup.Auth.cs的样子:

        var config = new HttpConfiguration();

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
          );

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        var builder = new ContainerBuilder();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<XXX>().As<IXXX>().InstancePerRequest();

        var container = builder.Build();

        //I've tried  both approached here!
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); 
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(webApiConfig);
        app.UseWebApi(webApiConfig);

这是我的OAuth提供商代码:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public SimpleAuthorizationServerProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");
        _publicClientId = publicClientId;
    }

    public IXXX XXX
    {
        get { return (IXXX)(_xxx??GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IXXX))); }
        set { _xxx= value; }
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        //Dependency IXXX used here
    }

    private readonly string _publicClientId;
    private IXXX _xxx;
}

2 个答案:

答案 0 :(得分:1)

您可以使用OwinContext.GetAutofacLifetimeScope()

查看nuget包: http://alexmg.com/owin-support-for-the-web-api-2-and-mvc-5-integrations-in-autofac/

答案 1 :(得分:0)

有趣的是,我正在解决类似的问题并使用以下OSS库来实现这一目标:https://github.com/DotNetDoodle/DotNetDoodle.Owin.Dependencies

这是一个用于OWIN中间件的 IoC容器适配器,它将请求级容器放入OWIN中间件的环境字典中。然后可以从OWIN中间件实现中访问该容器,从中可以解析每个请求范围的服务。

这取自github存储库的文档:

public override async Task Invoke(IOwinContext context)
{
    IServiceProvider requestContainer = context.Environment.GetRequestContainer();
    IRepository repository = requestContainer.GetService(typeof(IRepository)) as IRepository;

    // use repos
}

以下附加链接可能对您有用:

希望其中一些对您有帮助。