I’m trying to autowire up my application using Autofac. All is fine apart from the fact I have an abstract generic type such as:
public abstract class Transformer<TModel>
{
// Some abstract methods
}
With it implemented as:
public class EventTransformer : Transformer<Event>
{
// implementation of methods
}
I’m autowiring up the application with:
builder.RegisterAssemblyTypes(typeof (MyAssemblyName).Assembly)
.InstancePerLifetimeScope();
Autofac will then throw an error when resolving this type of class:
public class RandomClass<TModel>
{
public RandomClass(Transformer<TModel> transformer()
{
// Constructor code
}
}
I get the error below (simplified). I can register the EventTransformer manually as Transformer < Event > and everything works fine, but I don’t want to have to register it manually, I should be able to do it automatically so I can simply create a new class and it’s straight into the application.
The requested service Transformer`1[[Event]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
I did try and use the method .AsImplementedInterfaces() when registering the classes but it didn’t seem to work.
So what should I be doing to accomplish this? Also for bonus points, I have no way of knowing what Autofac is registering and what it’s registering it as. Is there anyway of doing this?
You need to register the open generic types with the
AsClosedTypesOfmethod during assembly scanning:And you can get the registered components with: