Autofac: Open generics and base interfaces

185 Views Asked by At

Given the following interfaces and classes, is there a way in Autofac to

  • Register a Provider<T> for all classes that have a ProviderAttribute, with T being the type of such a class (Think registering open generics and resolving them with Autofac's MakeGenericType())
  • Inject these registered providers as, drum roll, IEnumerable<IProviderBase> into the constructor of other classes

Overview:

public class ProviderAttribute : Attribute { }

public interface IProviderBase
{
    Type Type { get; }
}

public interface IProvider<T> : IProviderBase
{
    DoSomething(T t);
}

public class Provider<T> : IProvider<T>
{
    public Type Type
    {
        get { return typeof (T); }
    }

    public DoSomething(T t)
    {
        //...
    }
}
1

There are 1 best solutions below

0
On

I have come up with a crude solution:

var types = GetProviderTypes();

foreach (var type in types)
{
    var t = typeof (Provider<>).MakeGenericType(type);
    builder.RegisterType(t).As<IProviderBase>();
}