我似乎不能在我的DependencyResolver中使用OAuthAuthorizationServerProvider。
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;
}
发布于 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/
https://stackoverflow.com/questions/25047233
复制相似问题