4

描述我有一个遗留类型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。

4

1 回答 1

5

如果您将“解析器”配置为使用 RequestLifetime 而不是 ApplicationContainer,那么一切都应该按预期工作。

这意味着您的 IContainer 参数必须更改为 ILifetimeScope。

我不确定注入 ASMX 依赖项的更好方法,可能有一个,但我认为 Autofac 不支持它。

于 2010-03-02T08:06:30.470 回答