0

I am doing a very simple stuff but not working. I have,

public class A : IA
{
}

public interface IA
{
}

public class B<T> where T : IA
{

}

Now I am using Autofac to register this,

        builder.Register<B<IA>>(b =>
        {
            return new B<A>();
        });

But I am getting this error,

Cannot implicitly convert type 'B<A>' to 'B<IA>'?

Cannot convert lambda expression to delegate type 'System.Func<Autofac.IComponentContext,B<IA>>' because some of the return types in the block are not implicitly convertible to the delegate return type
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

2 Answers2

1

Given the classes you're working with, it looks like you'll just want to allow generic arguments to Register be determined by the compiler:

builder.Register(b => new B<A>());

Classes that take a B<A> as a dependency, with then get the correct B<A> instance. It doesn't make sense for anything to take B<IA> as a dependency, generics don't work that way. If that's what you intended to do, you would need to create an interface for B<T> instead, which removed any need to specify any generic type.

So:

public interface IB
{
}

public class B<T> : IB where T : IA
{

}

Then any classes that needed to take a dependency to B<T> would actually take a dependency to IB.

Update

OpenGenerics in autofac may also help depending on how you intend to use these classes of yours. Take a look at the example on their site, which will allows nice control of generic types which are registered through the RegisterGeneric() method.

Matt Tester
  • 4,663
  • 4
  • 29
  • 32
1

I think you missing the feature Covariance and Contravariance.

   public class A : IA
   {
   }

   public interface IA<out T>
   {
   }

   public class B where T : IA
   {
   }

Related link:

Community
  • 1
  • 1
cat916
  • 1,363
  • 10
  • 18