Home > Mobile >  How to register and access all services implementing a generic interface?
How to register and access all services implementing a generic interface?

Time:08-21

The generic interface:

public interface IEntityFactory<T>
{
    public Task<IEnumerable<T>> Sample();
}

The services:

public class RegionFactory : IEntityFactory<Region>
{
    public async Task<IEnumerable<Region>> Sample()
    {
        // return list of Regions.
    }
}

public class UserFactory : IEntityFactory<User>
{
    public async Task<IEnumerable<User>> Sample()
    {
        // return list of Users.
    }
}

How do I register these services in such a way that I can then access all of them as an enumerable, and call the Sample method on each. It's okay if the return type of Sample is something non-specific like Task<IEnumerable<object>>.

I've tried many combinations of registration and access, but I can't seem to find a working solution.

CodePudding user response:

This doesn't work. You have to create a new non-generic interface that has a non-generic method like:

public interface IEntityFactory
{
    public Task<System.Collections.IEnumerable> Sample();
}

Now all your factories have to implement this interface also and you can consume it in your service with IEnumerable<IEntityFactory>.

Depending on your structure you could additionally create a generic abstract base class that implements both interfaces and needs only an implementation of the generic part and does the non-generic by herself:

public abstract class EntityFactoryBase<T> : IEntityFactory<T>, IEntityFactory
{
    public abstract Task<IEnumerable<T>> Sample();

    async Task<System.Collections.IEnumerable> IEntityFactory.Sample()
    {
        return await Sample();
    }
}

By this approach your factories derive from the base class and have only to implement the one interface method as before, but in your receiving services you can also consume the non-generic interface.

  • Related