Search code examples
c#autofac

Autofac Keyed/Named methods do not provide overload with service mapping func


The As method provides an overload with a Func<Type, Type> serviceMapping parameter, but the Keyed and Named methods do not. They only provide Func<Type, object> serviceKeyMapping and Func<Type, string> serviceNameMapping parameters, respectively.

However, I want to register a set of types with RegisterAssemblyTypes using the same key for all of the types, but using a different interface determined by the type itself. I was expecting to find a method overload such as Keyed(object serviceKey, Func<Type, Type> serviceMapping) or Keyed(Func<Type, object> serviceKeyMapping, Func<Type, Type> serviceMapping).

Is this an oversight in the API design? Or am I missing something?


Solution

  • It seems that the API doesn't have such feature. You could however use the As(Func<Type, Service> serviceMapping) overload with a KeyedService object.

    For example

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

    KeyedService is in Autofac.Core namespace. There is no NamedService object but you can use a KeyedService with a string