CSharp · Console
using Autofac;
using Autofac.Features.Variance;
using DryIoc;
using System;
using System.Collections.Generic;
namespace DiVariance
{
public interface IQuery<in TIn, out TOut>
{
IReadOnlyCollection<TOut> Get(TIn key);
}
public class FakeRepository : IQuery<object, string>
{
public IReadOnlyCollection<string> Get(object key)
{
return new[] { key.ToString() };
}
}
public class Program
{
public static void Main(string[] args)
{
IQuery<string, object> service;
service = new FakeRepository(); // This works fine
Console.WriteLine("Poor man's IoC: {0}", string.Join(",", service.Get("42")));
try
{
var autofacBuilder = new Autofac.ContainerBuilder();
autofacBuilder.RegisterSource(new ContravariantRegistrationSource());
autofacBuilder.RegisterAssemblyTypes(typeof(FakeRepository).Assembly).AsImplementedInterfaces();
service = autofacBuilder.Build().Resolve<IQuery<string, object>>(); // unable to resolve
Console.WriteLine("Autofac: {0}", string.Join(",", service.Get("42")));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
try
{
var dryIocContainer = new DryIoc.Container();
dryIocContainer.RegisterMany(new[] { typeof(FakeRepository).Assembly });
var service1 = dryIocContainer.Resolve<IQuery<string, object>>(); // unable to resolve
Console.WriteLine("DryIoc: {0}", string.Join(",", service1.Get("42")));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}