0

I have a base class with multiple implementations and I would like to be able to register all the implementations in a look similar to Registering by Convention.

I am able to get all the implementations of the base class but when I try to actually register them I get the following exception:

System.ArgumentException: 'Open generic service type 'Bento.SearchContent.EventListener.Infrastructure.Index`1[T]' requires registering an open generic implementation type.'

public abstract class Index<T>
    where T : class
{
   ....        
}

sample subclass:

public class SurveyChangedIndex : Index<SurveyChanged>
{
   ....
}

sample function:

public static void RegisterIndexing()
        {
            var indexBase = typeof(Index<>);
            GetAllDescendantsOf(Assembly.GetAssembly(indexBase), indexBase)
                .ForEach(indexType => { _serviceCollection.AddSingleton(indexBase, indexType); });

            _serviceCollection.AddTransient<IIndexResolver, IndexResolver>(sp => new IndexResolver(sp));
        }
2
  • You may want to add the asp.net-core tag. .NET Core isn't just for ASP.NET... Commented Jan 15, 2018 at 17:33
  • 1
    Basically, the standard IoC is very basic and requires you to register all of the different type variants separately. Commented Jan 15, 2018 at 19:05

1 Answer 1

1

The following although not pretty works.

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApp3
{
    public class Index<T> where T : class { }

    public class A { }

    public class AIndex : Index<A> { }

    public class B { }

    public class BIndex : Index<B> { }

    class Program
    {

        static void Main(string[] args)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            new Type[] { typeof(AIndex), typeof(BIndex) }.ToList()
                .ForEach(t =>
                {
                    serviceCollection.AddSingleton(typeof(Index<>).MakeGenericType(t.BaseType.GetGenericArguments()), t);
                });

            var sp = serviceCollection.BuildServiceProvider();
            var aIndex = sp.GetService(typeof(Index<A>));
            var bIndex = sp.GetService(typeof(Index<B>));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.