Alex Rivera | Logout

Autofac: Resolving variant types with both in and out type arguments

Asked 2011-09-06T17:31:07.477
9

This question is a follow up of my previous question: Autofac: Hiding multiple contravariant implementations behind one composite.

I'm trying to find the boundries of what we can do with Autofac's covariance and contravariance support. I noticed that Autofac's ContravariantRegistrationSource only supports generic interfaces with a single generic parameter that is marked with the in keyword. This seems to limit the usefulness of this feature, and I'm wondering if Autofac has other ways in extending the support of covariance and contravariance.

I must admit that I'm not asking this because of a real application design I'm working of. I'm deliberately trying to find Autofac's limits for the sake of education.

So consider the following interface:

public interface IConverter<in TIn, out TOut>
{
    TOut Convert(TIn value);
}

And the following implementation:

public class ObjectToStringConverter : IConverter<object, string>
{
    string IConverter<object, string>.Convert(object value)
    {
        return value.ToString();
    }
}

And the following registation:

var builder = new ContainerBuilder();

builder.RegisterSource(new ContravariantRegistrationSource());

builder.RegisterType<ObjectToStringConverter>()
    .As<IConverter<object, string>>();

var container = builder.Build();

With this design and configuration, I'd expect to be able to do this:

// This call succeeds because IConverter<object, string> is
// explicitly registered.
container.Resolve<IConverter<object, string>&
Edit
Report

1 Answer

4

I think this is a limitation we're unlikely to overcome in Autofac, but it is interesting to explore.

We can do contravariant 'resolve' because given a generic type argument we can find all of the base/interface types to which that argument would be assignable. That is, given string we can search for implementations for object, IComparable etc.

Going in the opposite direction - from an argument type to all of its subclasses - isn't so easy. Given object we'd need some way to look for everything else.

It may be possible to use knowledge of the concrete components registered in the container, e.g. scan all components looking for possible implementations and work backwards, but this isn't great for Autofac because we rely on a 'pull' model to lazily create components in many cases.

Hope this is food for thought, interested to see what you come up with.

answered 2011-09-08T04:40:04.283

Your Answer