首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用AutofacWebApiDependencyResolver和WebAPI 2.1发布

使用AutofacWebApiDependencyResolver和WebAPI 2.1发布
EN

Stack Overflow用户
提问于 2014-07-30 21:24:16
回答 2查看 2.4K关注 0票数 2

我似乎不能在我的DependencyResolver中使用OAuthAuthorizationServerProvider。

代码语言:javascript
运行
复制
DependencyResolver.Current

返回我不使用的MVC版本,并且

代码语言:javascript
运行
复制
GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IXXX))

引发以下错误:

从请求实例的作用域中看不到带有与“AutofacWebRequest”匹配的标记的范围。这通常表示SingleInstance()组件(或类似的场景)请求按-HTTP请求注册的组件。在web集成下,总是从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,而不是从容器本身请求依赖项。

如果我做错了什么,或者我只是不能在我尝试的时候使用依赖关系,有什么想法吗?

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

代码语言:javascript
运行
复制
        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提供程序代码:

代码语言:javascript
运行
复制
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;
}
EN

Stack Overflow用户

发布于 2014-11-11 19:29:30

您可以使用OwinContext.GetAutofacLifetimeScope()

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

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25047233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档