首页 > 解决方案 > Autofac Keyed/Named 方法不提供服务映射函数的重载

问题描述

As方法提供带Func<Type, Type> serviceMapping参数的重载,但KeyedandNamed方法不提供。它们仅分别提供Func<Type, object> serviceKeyMappingFunc<Type, string> serviceNameMapping参数。

但是,我想注册一组类型,RegisterAssemblyTypes对所有类型使用相同的键,但使用由类型本身确定的不同接口。我期待找到一个方法重载,例如Keyed(object serviceKey, Func<Type, Type> serviceMapping)or Keyed(Func<Type, object> serviceKeyMapping, Func<Type, Type> serviceMapping)

这是 API 设计中的疏忽吗?还是我错过了什么?

标签: c#autofac

解决方案


API似乎没有这样的功能。但是,您可以将As(Func<Type, Service> serviceMapping)重载与KeyedService对象一起使用。

例如

builder.RegisterAssemblyTypes(typeof(Parent).Assembly)
        .Where(t => t.IsAssignableTo<ICommon>())
        .As(t => new KeyedService(keyObject, t.GetType().GetInterfaces()[0]));

KeyedServiceAutofac.Core命名空间中。没有NamedService对象,但您可以将 aKeyedService与 a 一起使用string


推荐阅读