Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac Resolve Open Generic Interface with Open Generic Class

So I have an interface and class:

public interface IMyInterface<T> where T : ISomeEntity {}

public class MyClass<T> : IMyInterface<T>
    where T : ISomeEntity {}

I will have some class that calls for it:

public class SomeClass : ISomeClass
{
    public SomeClass (IMyInterface<AuditEntity> myInterface) {}
}

I've done all sorts of things to get it to register the open generic interface and class with no luck.

I just want to say something like:

container.RegisterType(typeof(MyClass<>)).As(typeof(IMyInterface<>));

It would be annoying if I have to go through and explicitly do something like:

container.RegisterType<MyClass<AuditEntity>>().As<IMyInterface<AuditEntity>>();

Shouldn't this be trivial?

like image 489
Callum Linington Avatar asked Dec 19 '22 01:12

Callum Linington


2 Answers

You have to use the RegisterGeneric method see Registration Concepts - Open Generic Components

Something like this should works :

builder.RegisterGeneric(typeof(MyClass<>)).As(typeof(IMyInterface<>)); 
like image 138
Cyril Durand Avatar answered Jan 23 '23 10:01

Cyril Durand


Yes it is trivial with container.RegisterGeneric:

container.RegisterGeneric(typeof(MyClass<>)).As(typeof(IMyInterface <>));

You also seem to have your interface and class switched in the examples in your question. The registration should start with the type to want to register (e.g. MyClass) followed by the type you it to be registered as (e.g. IMyInterface).

like image 33
shf301 Avatar answered Jan 23 '23 09:01

shf301