Brent Arias
Brent Arias

Reputation: 30185

"Reverse-Resolution" with an Ioc Container?

Instead of registering an interface-to-class binding, I want to register a class and have the IOC container implicitly register the interface(s) associated with that class. I'd like to know if any IOC container can do this, though I specifically need the answer for Unity.

To make clear what I'm after, notice:

public interface IFred
{
    int Go();
}
public class Fred : IFred
{
    public int Go()
    {
        return 1;
    }
}

class Program
{
    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();

        container.RegisterType<Fred>();     //contra-variant registration?
        IFred foo = container.Resolve<IFred>();  //variant resolution?
    }
}

In the above example, I want a "Fred" instance returned, even though I did not explicitly register an IFred mapping.

Upvotes: 2

Views: 95

Answers (1)

qujck
qujck

Reputation: 14578

I know of a couple (not Unity though sorry)

Autofac:

ContainerBuilder builder = new ContainerBuilder();
builder
    .RegisterType<Fred>()
    .AsImplementedInterfaces();

and Castle Windsor:

WindsorContainer container = new WindsorContainer();
container.Register(
    Classes
        .From(typeof(Fred))
        .Pick()
        .LifestyleTransient()
        .WithServiceAllInterfaces());

Upvotes: 2

Related Questions