Search code examples
asp.net-core.net-coreasp.net-core-mvcautofacautofac-configuration

Autofac Register closed types and retrieve them at run time


I have an Interface that will take in a generic type T

 internal interface IQuestion<T> where T : IWithOptionsId
 {
     Task<T> Provide(Guid id);
 }

Following by that I will implement this interface in multiple classes. For example

public class SomeProvider : IQuestion<OptionsClass>
{
    private readonly IRepository _repository;

    public SomeProvider(IRepository repository)
    {

        _repository = repository;
    }

    public async Task<OptionsClass> Provide(Guid id)

    ...
}

To register this with outofac I used this

Autofac.RegisterAssemblyTypes(
        Assembly.GetExecutingAssembly())
    .AsImplementedInterfaces()
    .AsClosedTypesOf(typeof(IQuestion<>));

My question is this. I have multiple instances for this interface. How do I access different instance once at the run time? If my IQuestion<T> will take in Options class and also it will take in Answer class how can I get an instance of those classes during run time?


Solution

  • I'm pretty sure you can just inject the instance itself. Not great practice, but it should work:

    public SomeClass(SomeProvider<OptionsClass> provider)
    

    You could also try creating a named instance when you register it, and inject that. See this and this.