Assuming you are using Asp.Net Core project type with Visual Studio 2017
Lets say you have the following defination of an interface:
public interface IAuthenticationProvider
{
}
with implementing classes like so:
public class WindowsAuthentication : IAuthenticationProvider { }
public class NTMLAuthentication : IAuthenticationProvider { }
public class KerberosAuthentication : IAuthenticationProvider { }
public class CustomAuthentication : IAuthenticationProvider { }
So far so good. Now to resolve the dependencies for the types implementing the same interface I would use the custom resolver class with its interface:
public interface IAuthenticationResolver
{
IAuthenticationProvider GetProvider(Type type);
}
and its implementation:
public class AuthenticationResolver : IAuthenticationResolver
{
private readonly IServiceProvider services;
public AuthenticationResolver(IServiceProvider services)
{
this.services = services;
}
public IAuthenticationProvider GetProvider(Type type)
{
return this.services.GetService(type) as IAuthenticationProvider;
}
}
In your Startup
class, under ConfigureServices
register these types
services.AddTransient<IAuthenticationResolver, AuthenticationResolver>();
services.AddTransient<WindowsAuthentication>();
services.AddTransient<KerberosAuthentication>();
services.AddTransient<NTMLAuthentication>();
services.AddTransient<CustomAuthentication>();
Of course you can use Scopped if thats what you need.
Once this is all set, go back to your controller / client class where the dependencies are injected:
public class HomeController : Controller
{
private readonly Dictionary<string, IAuthenticationProvider> authProvidersDictionary;
public HomeController(IAuthenticationResolver resolver)
{
System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
this.authProvidersDictionary = new Dictionary<string, IAuthenticationProvider>();
foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
{
if (ti.ImplementedInterfaces.Contains(typeof(IAuthenticationProvider)))
{
this.authProvidersDictionary.Add(ti.Name, resolver.GetProvider(ti.UnderlyingSystemType));
}
}
}
}
Hope this helps!