【问题标题】:Autofac.Extras.DynamicProxy got error with public interfaceAutofac.Extras.DynamicProxy 与公共接口出错
【发布时间】:2018-07-31 17:52:49
【问题描述】:

我有公共接口和内部实现,

public interface IService
{
    ...
}
internal class Service: IService
{
    ...
}

我是通过

注册的
builder.RegisterAssemblyTypes(assembly)
       .EnableInterfaceInterceptors()
       .AsImplementedInterfaces()
       .AsSelf()

但我遇到了错误

组件Activator=Service(ReflectionActivator),Services=[~.IService,~.Service], Lifetime = Autofac.Core.Lifetime.MatchingScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope 不能使用接口拦截,因为它提供的服务不是公开可见的接口。检查您对组件的注册,以确保您没有启用拦截并将其注册为内部/私有接口类型。

为什么会出现此错误?我的界面是公开的。

【问题讨论】:

    标签: c# dependency-injection autofac castle-dynamicproxy


    【解决方案1】:

    使用AsSelf()方法时,容器会在当前注册的服务列表中添加具体类型。

    错误信息是

    不能使用接口拦截,因为它提供不公开可见的服务接口

    表示注册的所有服务都应该是一个接口,不是这样的。你可以在EnsureInterfaceInterceptionApplies method看到它

    private static void EnsureInterfaceInterceptionApplies(IComponentRegistration componentRegistration)
    {
        if (componentRegistration.Services
            .OfType<IServiceWithType>()
            .Select(s => new Tuple<Type, TypeInfo>(s.ServiceType, s.ServiceType.GetTypeInfo()))
            .Any(s => !s.Item2.IsInterface || !ProxyUtil.IsAccessible(s.Item1)))
        {
            throw new InvalidOperationException(
                string.Format(
                    CultureInfo.CurrentCulture,
                    RegistrationExtensionsResources.InterfaceProxyingOnlySupportsInterfaceServices,
                    componentRegistration));
        }
    }
    

    如果您删除 .AsSelf() 调用,代码将起作用。

    【讨论】:

    • 谢谢,但即使接口和实现都是公开的,我也会不断收到此错误。我对此感到困惑。
    • @Horosho 我也可以用公共界面重现它。如果您删除 AsSelf() 呼叫,它是否有效?
    • 报错信息是is not public visible interface,可以翻译为public AND interface
    • 是的,它可以在没有 AsSelf() 的情况下工作,现在我明白我的错了。
    猜你喜欢
    • 2013-09-17
    • 2017-07-25
    • 2018-11-24
    • 2011-06-18
    • 2019-01-26
    • 1970-01-01
    • 2011-08-29
    • 2016-05-03
    • 2017-06-08
    相关资源
    最近更新 更多