说明我有一个HttpRequestScoped
的旧版类型和一个使用该服务的旧版Web服务。为了解决传统问题中的服务,我有一个全局解析器。这在1.4中运行良好,现在我正在使用2.1.12我遇到DependencyResolutionException
。
代码在2.1.12中,我的Global.asax.cs:
builder.Register(c => new SomeLegacyType(HttpContext.Current)) // note: it relies on HttpContext.Current
.As<SomeLegacyType>()
.HttpRequestScoped();
_containerProvider = new ContainerProvider(builder.Build()); // this is my app's IContainerProvider
Setup.Resolver = new AutofacResolver(_containerProvider.ApplicationContainer);
Setup.Resolver是一个单例,它被设置为AutofacResolver,如下所示:
public class AutofacResolver : IResolver
{
private readonly IContainer _container;
public AutofacResolver(IContainer container)
{
_container = container;
}
public TService Get<TService>()
{
return _container.Resolve<TService>();
}
}
Web服务如下所示:
[WebService]
public LegacyWebService : WebService
{
[WebMethod(EnableSession=true)]
public String SomeMethod()
{
var legacyType = Setup.Resolver.Get<SomeLegacyType>();
}
}
异常调用Setup.Resolver.Get<SomeLegacyType>()
时出现以下异常:
Autofac.Core.DependencyResolutionException: No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[SomeAssembly.SomeLegacyType,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.
at Autofac.Core.Lifetime.MatchingScopeLifetime.FindScope(ISharingLifetimeScope mostNestedVisibleScope)
at Autofac.Core.Resolving.ComponentActivation..ctor(IComponentRegistration registration, IResolveOperation context, ISharingLifetimeScope mostNestedVisibleScope)
at Autofac.Core.Resolving.ResolveOperation.Resolve(ISharingLifetimeScope activationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.Resolve(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Container.Resolve(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.TryResolve(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)
附带问题是否有更好的方法在ASMX中注入属性,就像注入ASPX页面一样(而不是使用Setup.Resolver
)?由于遗留问题,我使用AttributedInjectionModule
。该模块似乎不适用于ASMX。
答案 0 :(得分:5)
如果您将“解析器”配置为使用RequestLifetime而不是ApplicationContainer,则所有应该按预期工作。
这意味着您的IContainer参数必须更改为ILifetimeScope。
我不确定注入ASMX依赖项的更好方法,可能有一个,但我不认为Autofac支持它。