Problem
I have a number of concrete, generic classes with two type arguments that implement a generic interface with one type argument. For example:
public interface ISomeService<T>
{
// ...
}
public class SomeService<TA, TB> : ISomeService<TA>
{
// ...
}
I register them using Autofac like this:
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterGeneric(typeof(SomeService<,>))
.As(typeof(ISomeService<>))
.InstancePerLifetimeScope();
var container = containerBuilder.Build();
When attempting to resolve an instance of ISomeService<Foo> like this:
var service = container.Resolve<ISomeService<Foo>>();
I get an Autofac.Core.Registration.ComponentNotRegisteredException exception saying that the requested service ISomeService`1[[Foo]] has not been registered.
Questions
- Is what I'm trying to do impossible using Autofac?
- If so, is there a workaround?
- If not, do other DI containers offer such a capability, e.g. SimpleInjector?
With Simple Injector, you can make register a partially-closed generic type as follows:
There is no other DI library that can handle this, but in this case there is a simple workaround for containers like Autofac; you can simply derive from the type: